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条)

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?