go如何判断key是否在slice中?

定义一个slice,想要判断key是否在slice中,怎么方便来实现?

代码如下:
func main(){

urls := []string{
    "https://www.aaa.com",
    "https://www.bbb.com",
    "https://www.ccc.com",
    "https://www.ddd.com/",
}
fmt.Println(urls[6])  

}
输出结果为:
panic: runtime error: index out of range

goroutine 1 [running]:
main.main()

有没有什么函数能直接判断key是否在 slice 中呢?

回复
阅读 13k
8 个回答

自己写一个吧。

func contains(s [] string, e string) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}

Go不熟悉呢,谢邀。

把你的index与切片长度比一下就不知道了?

这个要分两种情况,一种是排序的slice,一种是非排序的slice。不同的数组设计在查询的时候效率是完全不一样的,这个要根据你的业务情况选择。
可以参考garray这个包的实现:http://gf.johng.cn/container/...

粘贴下beego里slice相关的帮助函数

import (
    "math/rand"
    "time"
)

type reducetype func(interface{}) interface{}
type filtertype func(interface{}) bool

// InSlice checks given string in string slice or not.
func InSlice(v string, sl []string) bool {
    for _, vv := range sl {
        if vv == v {
            return true
        }
    }
    return false
}

// InSliceIface checks given interface in interface slice.
func InSliceIface(v interface{}, sl []interface{}) bool {
    for _, vv := range sl {
        if vv == v {
            return true
        }
    }
    return false
}

// SliceRandList generate an int slice from min to max.
func SliceRandList(min, max int) []int {
    if max < min {
        min, max = max, min
    }
    length := max - min + 1
    t0 := time.Now()
    rand.Seed(int64(t0.Nanosecond()))
    list := rand.Perm(length)
    for index := range list {
        list[index] += min
    }
    return list
}

// SliceMerge merges interface slices to one slice.
func SliceMerge(slice1, slice2 []interface{}) (c []interface{}) {
    c = append(slice1, slice2...)
    return
}

// SliceReduce generates a new slice after parsing every value by reduce function
func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{}) {
    for _, v := range slice {
        dslice = append(dslice, a(v))
    }
    return
}

// SliceRand returns random one from slice.
func SliceRand(a []interface{}) (b interface{}) {
    randnum := rand.Intn(len(a))
    b = a[randnum]
    return
}

// SliceSum sums all values in int64 slice.
func SliceSum(intslice []int64) (sum int64) {
    for _, v := range intslice {
        sum += v
    }
    return
}

// SliceFilter generates a new slice after filter function.
func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{}) {
    for _, v := range slice {
        if a(v) {
            ftslice = append(ftslice, v)
        }
    }
    return
}

// SliceDiff returns diff slice of slice1 - slice2.
func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{}) {
    for _, v := range slice1 {
        if !InSliceIface(v, slice2) {
            diffslice = append(diffslice, v)
        }
    }
    return
}

// SliceIntersect returns slice that are present in all the slice1 and slice2.
func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{}) {
    for _, v := range slice1 {
        if InSliceIface(v, slice2) {
            diffslice = append(diffslice, v)
        }
    }
    return
}

// SliceChunk separates one slice to some sized slice.
func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{}) {
    if size >= len(slice) {
        chunkslice = append(chunkslice, slice)
        return
    }
    end := size
    for i := 0; i <= (len(slice) - size); i += size {
        chunkslice = append(chunkslice, slice[i:end])
        end += size
    }
    return
}

// SliceRange generates a new slice from begin to end with step duration of int64 number.
func SliceRange(start, end, step int64) (intslice []int64) {
    for i := start; i <= end; i += step {
        intslice = append(intslice, i)
    }
    return
}

// SlicePad prepends size number of val into slice.
func SlicePad(slice []interface{}, size int, val interface{}) []interface{} {
    if size <= len(slice) {
        return slice
    }
    for i := 0; i < (size - len(slice)); i++ {
        slice = append(slice, val)
    }
    return slice
}

// SliceUnique cleans repeated values in slice.
func SliceUnique(slice []interface{}) (uniqueslice []interface{}) {
    for _, v := range slice {
        if !InSliceIface(v, uniqueslice) {
            uniqueslice = append(uniqueslice, v)
        }
    }
    return
}

// SliceShuffle shuffles a slice.
func SliceShuffle(slice []interface{}) []interface{} {
    for i := 0; i < len(slice); i++ {
        a := rand.Intn(len(slice))
        b := rand.Intn(len(slice))
        slice[a], slice[b] = slice[b], slice[a]
    }
    return slice
}

slice 和数组不同,slice中不会出现空洞。slice的元素删除使用s = append(s[:i], s[i+1:]...)

定义了一个slice,那么slice中的元素的index就是0~len(slice)-1。

也就是说,只要index < len(slice)-1,去请求就不会panic。

slice没有中没有key的概念,如果你指的是下标,可以这样:

if idx < len(urls){
    // key在urls中,可对数据进行操作
} else {
    // pass
}

不过更加Golang的用法是:

urls := make([string]struct{})

if url in urls{
    // do 
} else {
    // do 
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏