gpt4 book ai didi

go - 反射(reflect)值(value)问题

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:58 26 4
gpt4 key购买 nike

在尝试测试此业务功能时:

//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
}

我发现它没有通过我的合理性测试:

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

}

负责修复这些错误的人不知道是什么导致了错误,更不用说如何修复了,我和高级开发人员也不知道。所以,我试图 isolate the problem试图识别它。

我以为是

当我记录错误时,我认为它们是因为不知何故,valueslice.Index(i )。我试过了

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

但是失败了。我可以通过测试的唯一方法是使用 Int() 提取值并使用

var i int64 = 3

而不是文字 3,这是片状 af。

问题是什么以及我们如何解决它?

最佳答案

Index() method返回一个 reflect.Value。使用该值的 Interface() method获取其潜在值(value)并与之进行比较:

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
}

关于go - 反射(reflect)值(value)问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52538869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com