Go Slices
Slices are a key data type in Go, giving a more powerful interface to sequences than arrays. Unlike arrays, slices are typed only by the elements they contain (not the number of elements).
1. Creating Slices
An uninitialized slice is nil and has a length of 0.
2. The append Function
append returns a new slice containing one or more new values. It's the standard way to grow a slice.
3. Slicing Slices
Slices support a "copy" operator with the syntax slice[low:high]. This creates a new slice that points to a portion of the original.
4. Copying Slices
To create an entirely new, independent copy of a slice, use the built-in copy function.
Length vs Capacity
- Length: The number of elements currently in the slice.
len(s) - Capacity: The number of elements the underlying array can hold before needing to reallocate.
cap(s)
Summary: Array vs Slice
| Feature | Array | Slice |
|---|---|---|
| Size | Fixed (part of type) | Dynamic (resizable) |
| Declaration | [5]int |
[]int |
| Passing | Copied by value | Passed by reference |
| Usage | Rare | Very Common |