Slices
suggest changeA slice is a growable sequence of values of the same type.
Other languages call them arrays or vectors.
The memory used by a slice is a fixed-size array. A slice is a view into that array.
Slice has length and capacity.
Capacity is the number of elements from the slice's first element to the end of its underlying array.
Length is the current number of elements in the slice.
The difference between capacity and length is how many elements can be appended before append must allocate a new underlying array.
Zero value of a slice is nil.
Basics of slices
slice := make([]int, 0, 5)
// append element to end of slice
slice = append(slice, 5)
// append multiple elements to end
slice = append(slice, 3, 4)
fmt.Printf("length of slice is: %d\n", len(slice))
fmt.Printf("capacity of slice is: %d\n", cap(slice))
length of slice is: 3
capacity of slice is: 5
Optimize by pre-allocating slice
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents