zl程序教程

您现在的位置是:首页 >  其他

当前栏目

golang interface对象的比较会同时比较类型和值

2023-03-14 22:41:32 时间

今天使用以往的工具函数来判断对象是否存在于列表时,发现明明存在的元素,一直返回了 false,很奇怪,后来才想起来 interface类型的对象除了比较值,还会比较类型,类型不对,同样匹配不上。

func InArray(obj interface{}, array interface{}) bool {
    targetValue := reflect.ValueOf(array)
    switch reflect.TypeOf(array).Kind() {
    case reflect.Slice, reflect.Array:
        for i := 0; i < targetValue.Len(); i++ {
            if targetValue.Index(i).Interface() == obj {
                return true
            }
        }
    case reflect.Map:
        if targetValue.MapIndex(reflect.ValueOf(obj)).IsValid() {
            return true
        }
    }
    return false
}
func main(t *testing.T) {
    obj := int64(234) // int64类型
    arr := []int{234, 140, 13, 42, 319, 32, 523, 49, 380, 222}
    ret := InArray(obj, arr)
    fmt.Printf("result=%v
", ret)  // result=false
}

把 obj 对象改成 int 类型就能匹配上了

func main(t *testing.T) {
    obj := 234 // int类型
    arr := []int{234, 140, 13, 42, 319, 32, 523, 49, 380, 222}
    ret := InArray(obj, arr)
    fmt.Printf("result=%v
", ret)  // result=false
}

参考:刘丹冰大佬的 4、interface