Slices are flexible views into underlying arrays. They are defined as []T and have a length (len) and a capacity (cap).
Key operations:
- Slicing: Use
a[low:high] to create a slice. Defaults are 0 for low and len(a) for high. - Creation: Use
make([]T, length, capacity) to allocate a slice. - Appending: Use the built-in
append function to add elements. If capacity is insufficient, a new underlying array is allocated. - Zero Value: The zero value of a slice is
nil, with length and capacity of 0.
// Create slice with length 5
a := make([]int, 5)
// Create slice with length 0 and capacity 5
b := make([]int, 0, 5)
// Append elements
slice = append(slice, elem1, elem2)
slice = append(slice, anotherSlice...)
// Append string to byte slice
slice = append([]byte("hello "), "world"...)