doupuxuan5784 2018-09-27 14:01
浏览 88
已采纳

Reflect.Value问题

In trying to test this business func:

//IsInSlice works like Array.prototype.find in JavaScript, except it
// returns -1 if `value` is not found. (Also, Array.prototype.find takes
// function, and IsInSlice takes `value` and `list`)
func IsInSlice(value interface{}, list interface{}) int {
    slice := reflect.ValueOf(list)

    for i := 0; i < slice.Len(); i++ {
        if slice.Index(i) == value {
            return i
        }
    }
    return -1
}

I find that it fails my sanity tests:

func TestIsInSlice(t *testing.T) {
    digits := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    slice := digits[3:8] // returns {3,4,5,6,7}

    type args struct {
        value interface{}
        list  interface{}
    }
    tests := []struct {
        name string
        args args
        want int
    }{
        {
            name: "SanityTest",
            args: args{value: 3,
                list: []int{3, 4, 5, 6, 7},
            },
            want: 0,
        },
        {
            name: "ElementAtEnd",
            args: args{
                value: 5,
                list:  slice,
            },
            want: 3,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := IsInSlice(tt.args.value, tt.args.list); got != tt.want {
                t.Errorf("IsInSlice() = %v, want %v", got, tt.want)
            }
        })
    }

}

The person responsible for fixing these bugs has no idea what is causing the bug, let alone how to fix it, and neither do me or the senior dev. So, I attempted to isolate the problem to try to identify it.

What I thought it was

When I logged the bugs, I thought they were because somehow, the value was being compared to the reflect.Value returned by slice.Index(i). I tried

reflect.DeepEqual(slice.Index(i), value)

but that fails. The only way I could get passing test is to use Int() to extract the value and use

var i int64 = 3

instead of the literal 3, which is flaky af.

What is the issue and how do we fix it?

  • 写回答

2条回答 默认 最新

  • dqy92287 2018-09-27 14:12
    关注

    The Index() method returns a reflect.Value. Use that value's Interface() method to get its underlying value and compare to that:

    func IsInSlice(value interface{}, list interface{}) int {
        slice := reflect.ValueOf(list)
        for i := 0; i < slice.Len(); i++ {
            if slice.Index(i).Interface() == value {
                return i
            }
        }
        return -1
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿