Essential Go Slices  Suggest an edit

Create a slice

Most of the time you don't have to explicitly create a slice. Zero value of a slice is nil and append works with that:

var a []int
fmt.Printf("a is %#v\n", a)
a = append(a, 3)
fmt.Printf("a is %#v\n", a)

There are 2 ways to create an empty slice:

var nilSlice []bool
empty1 := []bool{}
empty2 := make([]bool{})
fmt.Printf("nilSlice is %#v\n", nilSlice)
// empty slice is different than nil slice
fmt.Printf("empty1 is %#v\n", empty1)
fmt.Printf("empty2 is %#v\n", empty2)

Empty slice is different than nil slice.

Create statically pre-allocated slice:

a := []int{3, 1, 4, 1}
fmt.Printf("a has %d elements\n", len(a)

Pre-allocate slice filled with zero values:

a := make([]string, 4)
fmt.Printf("a has %d elements\n", len(a))

If you know the expected size of the slice, you can pre-allocate space for its content, which helps performance:

n := 30
a := make([]int, 0, n)
fmt.Printf("a has lenght %d and capacity %d\n", len(a), cap(a))
for i := 0; i < n; i++ {
	a = append(a, i)
}
fmt.Printf("a has lenght %d and capacity %d\n", len(a), cap(a))

  ↑ ↓ to navigate     ↵ to select     Esc to close