美文网首页
go_in_array写法

go_in_array写法

作者: RedHatMe | 来源:发表于2020-07-29 14:06 被阅读0次

// 判断某一个值是否含在切片之中
func InArray(need interface{}, haystack interface{}) bool {
    switch key := need.(type) {
    case int:
        for _, item := range haystack.([]int) {
            if item == key {
                return true
            }
        }
    case string:
        for _, item := range haystack.([]string) {
            if item == key {
                return true
            }
        }
    case int64:
        for _, item := range haystack.([]int64) {
            if item == key {
                return true
            }
        }
    case float64:
        for _, item := range haystack.([]float64) {
            if item == key {
                return true
            }
        }
    default:
        return false
    }
    return false
}
//判断某一个值是否含在切片之中
func In_Array(val interface{}, array interface{}) (exists bool, index int) {
    exists = false
    index = -1

    switch reflect.TypeOf(array).Kind() {
    case reflect.Slice:
        s := reflect.ValueOf(array)

        for i := 0; i < s.Len(); i++ {
            if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
                index = i
                exists = true
                return
            }
        }
    }

    return
}

image.png

相关文章

网友评论

      本文标题:go_in_array写法

      本文链接:https://www.haomeiwen.com/subject/fumhrktx.html