有没有办法检查切片/映射是否存在值?
我想为切片添加一个值only如果是的话not存在于切片中。
这可行,但看起来很冗长。有一个更好的方法吗?
orgSlice := []int{1, 2, 3}
newSlice := []int{}
newInt := 2
newSlice = append(newSlice, newInt)
for _, v := range orgSlice {
if v != newInt {
newSlice = append(newSlice, v)
}
}
newSlice == [2 1 3]
您的方法每次插入都需要线性时间。更好的方法是使用map[int]struct{}
。或者,您也可以使用map[int]bool
或类似的东西,但是空的struct{}
其优点是不占用任何额外空间。所以map[int]struct{}
是一组整数的流行选择。
Example:
set := make(map[int]struct{})
set[1] = struct{}{}
set[2] = struct{}{}
set[1] = struct{}{}
// ...
for key := range(set) {
fmt.Println(key)
}
// each value will be printed only once, in no particular order
// you can use the ,ok idiom to check for existing keys
if _, ok := set[1]; ok {
fmt.Println("element found")
} else {
fmt.Println("element not found")
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)