Go cheatsheet - Slice Utilities

·

2 min read

Slice

Empty a slice

a := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
a = a[:0]
// or
a = nil

Prepend

b := []int{2, 3, 4}
b = append([]int{1}, b...)

Remove

a = append(a[:i], a[i+1:]...)

Insert at index

s = append(s, 0)
copy(s[i+1:], s[i:])
s[i] = x

Index/Find element

func Index(vs []string, t string) int {
    for i, v := range vs {
        if v == t {
            return i
        }
    }
    return -1
}

Include/Contain

func Include(vs []string, t string) bool {
    return Index(vs, t) >= 0
}

Any & All

func Any(vs []string, f func(string) bool) bool {
    for _, v := range vs {
        if f(v) {
            return true
        }
    }
    return false
}

func All(vs []string, f func(string) bool) bool {
    for _, v := range vs {
        if !f(v) {
            return false
        }
    }
    return true
}

Filter

func Filter(vs []string, f func(string) bool) []string {
    vsf := make([]string, 0)
    for _, v := range vs {
        if f(v) {
            vsf = append(vsf, v)
        }
    }
    return vsf
}

Map

func Map(vs []string, f func(string) string) []string {
    vsm := make([]string, len(vs))
    for i, v := range vs {
        vsm[i] = f(v)
    }
    return vsm
}