Create a slice
suggest changeMost 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)
a is []int(nil)
a is []int{3}
There are 2 ways to create an empty slice:
var nilSlice []bool
empty1 := []bool{}
empty2 := make([]bool, 0)
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)
nilSlice is []bool(nil)
empty1 is []bool{}
empty2 is []bool{}
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))
a has 4 elements
Pre-allocate slice filled with zero values:
a := make([]string, 4)
fmt.Printf("a has %d elements\n", len(a))
a has 4 elements
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))
a has lenght 0 and capacity 30
a has lenght 30 and capacity 30
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents