Examples in Go
Go slices are commonly used to represent a List.
package main

import "fmt"

func main() {
    // Initializing a slice.
    s := make([]string, 3)
    fmt.Println("emp:", s)

    // Setting and getting values by index.
    s[0] = "a"
    s[1] = "b"
    s[2] = "c"
    fmt.Println("set:", s)
    fmt.Println("get:", s[2])

    // len returns the length of the slice as expected.
    fmt.Println("len:", len(s))

    // Adding elements to the end of the slice.
    s = append(s, "d")
    s = append(s, "e", "f")
    fmt.Println("apd:", s)

    // Copying slices.
    c := make([]string, len(s))
    copy(c, s)
    fmt.Println("cpy:", c)

    // Slices support a "slice" operator with the syntax slice[low:high]
    l := s[2:5]
    fmt.Println("sl1:", l)

    l = s[:5]
    fmt.Println("sl2:", l)

    l = s[2:]
    fmt.Println("sl3:", l)

    t := []string{"g", "h", "i"}
    fmt.Println("dcl:", t)

    // Slices can be composed into multi-dimensional data structures.
    twoD := make([][]int, 3)
    for i := 0; i < 3; i++ {
        innerLen := i + 1
        twoD[i] = make([]int, innerLen)
        for j := 0; j < innerLen; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2d: ", twoD)
}
Last Run  :
emp: [  ]
set: [a b c]
get: c
len: 3
apd: [a b c d e f]
cpy: [a b c d e f]
sl1: [c d e]
sl2: [a b c d e]
sl3: [c d e f]
dcl: [g h i]
2d:  [[0] [1 2] [2 3 4]]
package main

import (
	"fmt"
)

func main() {
	// Create a nil slice.
	var a []int
	fmt.Println(a)

	// Create slice literal.
	b := []int{1, 2, 3}
	fmt.Println(b)

	// Create slice using make.
	c := make([]int, 5)
	fmt.Println(c)

	// Create slice from nil.
	d := append([]int(nil), 1, 2, 3)
	fmt.Println(d)
}
Last Run  :
[]
[1 2 3]
[0 0 0 0 0]
[1 2 3]
Copy a list by creating a new list and copying all the values over to the new list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}

	// Method #1
	dest := make([]int, len(s))
	copy(dest, s)
	fmt.Println(dest)

	// Method #2
	dest2 := append([]int(nil), s...)
	fmt.Println(dest2)

	// Method #3
	dest3 := append(s[:0:0], s...)
	fmt.Println(dest3)
}
Last Run  :
[1 2 3 4 5]
[1 2 3 4 5]
[1 2 3 4 5]
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}

	insertAtIdx := 2
	s = append(s[:insertAtIdx], append([]int{999}, s[insertAtIdx:]...)...)
	fmt.Println(s)
}
Last Run  :
[1 2 999 3 4 5]
Insert a value at the start of the list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s = append([]int{-99}, s...)
	fmt.Println(s)
}
Last Run  :
[-99 1 2 3 4 5]
Insert a value at the end of the list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s = append(s, 6)
	fmt.Println(s)
}
Last Run  :
[1 2 3 4 5 6]
Insert the values of another list at the index of the working list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s2 := []int{6, 7, 8, 9, 10}

	insertIdx := 3
	s = append(s[:insertIdx], append(s2, s[insertIdx:]...)...)
	fmt.Println(s)
}
Last Run  :
[1 2 3 6 7 8 9 10 4 5]
Insert the values of another list at the start of the working list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s2 := []int{6, 7, 8, 9, 10}

	s = append(s2, s...)
	fmt.Println(s)
}
Last Run  :
[6 7 8 9 10 1 2 3 4 5]
Insert the values of another list at the end of the working list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s2 := []int{6, 7, 8, 9, 10}

	s = append(s, s2...)
	fmt.Println(s)
}
Last Run  :
[1 2 3 4 5 6 7 8 9 10]
Get the size or length of the list.
package main

import (
	"fmt"
)

func main() {

	var a []int

	// In Go, the length of a nil slice is 0
	fmt.Println(len(a))

	a = append(a, 1, 2, 3)
	fmt.Println(len(a))
}
Last Run  :
0
3
package main

import (
	"fmt"
)

func main() {

	list := []string{"a", "b", "c"}
	fmt.Println(list[1])
}
Last Run  :
b
package main

import (
	"fmt"
)

func main() {

	list := []string{"a", "b", "c"}
	fmt.Println(list[0])
}
Last Run  :
a
package main

import (
	"fmt"
)

func main() {

	list := []string{"a", "b", "c"}
	fmt.Println(list[len(list)-1])
}
Last Run  :
c
package main

import (
	"fmt"
)

func main() {
	a := []int{1, 2, 3, 4, 5, 6, 7}
	sublist := a[0:5]
	fmt.Println(sublist)
}
Last Run  :
[1 2 3 4 5]
package main

import (
	"fmt"
)

func main() {
	a := []int{1, 2, 3, 4, 5, 6, 7}
	sublist := a[2:4]
	fmt.Println(sublist)
}
Last Run  :
[3 4]
package main

import (
	"fmt"
)

func main() {
	a := []int{1, 2, 3, 4, 5, 6, 7}
	sublist := a[3:len(a)]
	fmt.Println(sublist)
}
Last Run  :
[4 5 6 7]
Set value at index in a list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s[2] = 999
	fmt.Println(s)
}
Last Run  :
[1 2 999 4 5]
Sets the first value in the list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s[0] = 999
	fmt.Println(s)
}
Last Run  :
[999 2 3 4 5]
Sets the last value in the list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s[len(s)-1] = 999
	fmt.Println(s)
}
Last Run  :
[1 2 3 4 999]
package main

import "fmt"

func main() {
  
  s := []int{1, 2, 3, 4, 5}
  fmt.Println(s)
  
  removeIdx := 3
  s = append(s[:removeIdx], s[removeIdx+1:]...)
  fmt.Println(s)
}
Last Run  :
[1 2 3 4 5]
[1 2 3 5]
Remove the first value in a list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s = s[1:]
	fmt.Println(s)
}
Last Run  :
[2 3 4 5]
Removes the last value in the list.
package main

import (
	"fmt"
)

func main() {
	s := []int{1, 2, 3, 4, 5}
	s = s[:len(s)-1]
	fmt.Println(s)
}
Last Run  :
[1 2 3 4]
package main

import (
	"fmt"
	"sort"
)

func main() {

	fruit := []string{"Apple", "Banana", "Mango", "Orange"}

	// Custom sort based on the second letter of the word.
	sort.Slice(fruit, func(i, j int) bool {
		return fruit[i][1] < fruit[j][1]
	})

	fmt.Println(fruit)
}
Last Run  :
[Banana Mango Apple Orange]
package main

import (
	"fmt"
)

func main() {
	a := []int{1, 2, 3, 4, 5}
	for i := len(a)/2 - 1; i >= 0; i-- {
		opp := len(a) - 1 - i
		a[i], a[opp] = a[opp], a[i]
	}
	fmt.Println(a)
}
Last Run  :
[5 4 3 2 1]
Rearrange the values in a list in random order.
package main

import (
	"fmt"
	"math/rand"
	"time"
)

func main() {
	rand.Seed(time.Now().UnixNano())
	a := []int{1, 2, 3, 4, 5}
	for i := len(a) - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		a[i], a[j] = a[j], a[i]
	}
	fmt.Println(a)

	// You can also use rand.Shuffle
	b := []int{6, 7, 8, 9, 10}
	rand.Shuffle(len(b), func(i, j int) {
		b[i], b[j] = b[j], b[i]
	})
	fmt.Println(b)
}
Last Run  :
[2 4 3 1 5]
[10 6 8 7 9]
package main

import "fmt"

func main() {

    nums := []int{2, 3, 4}
    sum := 0
    for _, num := range nums {
        sum += num
    }
    fmt.Println("sum:", sum)

    for i, num := range nums {
        if num == 3 {
            fmt.Println("index:", i)
        }
    }

    for i, c := range "go" {
        fmt.Println(i, c)
    }
}
Last Run  :
sum: 9
index: 1
0 103
1 111
package main

import (
	"fmt"
)

func Equal(a, b []int) bool {
	if len(a) != len(b) {
		return false
	}
	for i, v := range a {
		if v != b[i] {
			return false
		}
	}
	return true
}

func main() {
	a := []int{1, 2, 3}
	b := []int{1, 2, 3, 4}
	c := []int{1, 2, 3}
	fmt.Println(Equal(a, b))
	fmt.Println(Equal(a, c))
}
Last Run  :
false
true
Find a value in a list by applying a predicate on each value.
package main

import (
	"fmt"
	"strings"
)

func FindStr(list []string, pred func(s string) bool) string {
	for _, s := range list {
		if pred(s) {
			return s
		}
	}
	return ""
}

func main() {

	list := []string{"slice", "of", "strings"}
	res := FindStr(list, func(s string) bool {
		return strings.HasPrefix(s, "o")
	})
	fmt.Println(res)
}
Last Run  :
of
Find the index of a value in by applying a predicate on each value.
package main

import (
	"fmt"
	"strings"
)

func FindStrIdx(list []string, pred func(s string) bool) int {
	for i, s := range list {
		if pred(s) {
			return i
		}
	}
	return -1
}

func main() {

	list := []string{"slice", "of", "strings"}
	res := FindStrIdx(list, func(s string) bool {
		return strings.HasPrefix(s, "o")
	})
	fmt.Println(res)
}
Last Run  :
1
Filters a list by applying a predicate to each value.
package main

import (
    "fmt"
    "strings"
)

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
}

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}

    fmt.Println(Filter(strs, func(v string) bool {
        return strings.Contains(v, "e")
    }))
}
Last Run  :
[peach apple pear]
package main

import (
    "fmt"
)

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

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

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}

    fmt.Println(Contains(strs, "grape"))
}
Last Run  :
false
package main

import (
    "fmt"
)

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

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}
    fmt.Println(Index(strs, "pear"))
}
Last Run  :
2
package main

import (
    "fmt"
    "strings"
)

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

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}

    fmt.Println(Any(strs, func(v string) bool {
        return strings.HasPrefix(v, "p")
    }))
}
Last Run  :
true
package main

import (
    "fmt"
    "strings"
)

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

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}

    fmt.Println(All(strs, func(v string) bool {
        return strings.HasPrefix(v, "p")
    }))
}
Last Run  :
false
package main

import (
    "fmt"
    "strings"
)

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
}

func main() {

    var strs = []string{"peach", "apple", "pear", "plum"}

    fmt.Println(Map(strs, strings.ToUpper))
}
Last Run  :
[PEACH APPLE PEAR PLUM]
Partitions the list into groups.
package main

import (
	"fmt"
)

func main() {
	a := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	// Here, we know how many paritions we need for grouping by even/odd numbers.
	partitions := make([][]int, 2)
	for _, n := range a {
		idx := n % 2
		partitions[idx] = append(partitions[idx], n)
	}
	fmt.Println(partitions)

	// Next we try grouping by first letter of a word.
	// Here, we use a map to access buckets by a key.
	b := []string{"orange", "apple", "grapefruit", "avocados"}
	partitions2 := map[string][]string{}
	for _, str := range b {
		key := string(str[0])
		partitions2[key] = append(partitions2[key], str)
	}
	fmt.Println(partitions2)
}
Last Run  :
[[0 2 4 6 8] [1 3 5 7 9]]
map[a:[apple avocados] g:[grapefruit] o:[orange]]
Get a list of lists for batch processing.
package main

import (
	"fmt"
)

func main() {

	actions := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
	batchSize := 3
	batches := make([][]int, 0, (len(actions)+batchSize-1)/batchSize)

	for batchSize < len(actions) {
		actions, batches = actions[batchSize:], append(batches, actions[0:batchSize:batchSize])
	}
	batches = append(batches, actions)
	fmt.Println(batches)
}
Last Run  :
[[0 1 2] [3 4 5] [6 7 8] [9]]