2.6. Slices
Basics
With a slice literal (e.g. []int{1, 2, 3}) and the short assignment we we can initialize a new slice.
Slices store multiple items of the same type.
| |
Output:
[2 3 5 7 11 13]
Length of slice: 6
Slice of structs
We can also store multiple instances of a struct.
| |
Output:
[{Christoph 48} {Susanne 35} {Peter 29}]
{Susanne 35}
Appending items
To add items to an existing slice you can use append. Notice that append does not modify the original slice, but returns a new one.
| |
Output:
Initial slice: [1 2 3]
Add one item: [1 2 3 4]
Add multiple items: [1 2 3 4 5 6 7]
Loops
In 2.2. Flow control we learned about the basic for loop. However if we want to loop over all the slice elements, we prefer to use range.
With range we can iterate over all items of a slice.
| |
Output:
0 2
1 4
2 8
In many cases we discard the index with _ because we only need the actual item:
| |
Output:
2
4
8
Links
- SliceTricks contains various examples (delete an item from slice, push to a slice, pop from a slice, etc.)
Last modified May 29, 2024: Merge pull request #205 from acend/renovate/actions-checkout-digest (cc47d9a)