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

报告相同问题?

悬赏问题

  • ¥20 西南科技大学数字信号处理
  • ¥15 有两个非常“自以为是”烦人的问题急期待大家解决!
  • ¥30 STM32 INMP441无法读取数据
  • ¥15 R语言绘制密度图,一个密度曲线内fill不同颜色如何实现
  • ¥100 求汇川机器人IRCB300控制器和示教器同版本升级固件文件升级包
  • ¥15 用visualstudio2022创建vue项目后无法启动
  • ¥15 x趋于0时tanx-sinx极限可以拆开算吗
  • ¥15 pyqt信号槽连接写法
  • ¥500 把面具戴到人脸上,请大家贡献智慧,别用大模型回答,大模型的答案没啥用
  • ¥15 任意一个散点图自己下载其js脚本文件并做成独立的案例页面,不要作在线的,要离线状态。