代码片段 #
slice #
contains #
func contains(s []int, e int) bool {
    for _, a := range s {
        if a == e {
            return true
        }
    }
    return false
}
使用 map[string] struct{}
#
参考:
最前面插入一个元素 #
// 最前面插入一个元素
x = append([]int{1}, x...)
// An allocation is only necessary when there is no spare slice capacity.
x = append(x, 0)
copy(x[1:], x)
x[0] = 1
参考:
找出元素位置 #
func SliceIndex(limit int, predicate func(i int) bool) int {
    for i := 0; i < limit; i++ {
        if predicate(i) {
            return i
        }
    }
    return -1
}
参考:
删除元素 #
使用 index 删除
// 保持有序
func remove(slice []int, s int) []int {
    return append(slice[:s], slice[s+1:]...)
}
// 无序
func remove(s []int, i int) []int {
    s[i] = s[len(s)-1]
    // We do not need to put s[i] at the end, as it will be discarded anyway
    return s[:len(s)-1]
}
使用元素值删除
func remove(s []string, e string) []string {
    result := s[:0]
    for _, item := range s {
        if item != e {
            result = append(result, item)
        }
    }
    return result
}
参考:
叶王 © 2013-2024 版权所有。如果本文档对你有所帮助,可以请作者喝饮料。