Go Slices
Grow a sequence with append and take a part of it.
package main
import "fmt"
func main() {
scores := []int{82, 91, 76}
scores = append(scores, 95)
fmt.Println(len(scores), scores[3])
fmt.Println(scores[1:3])
}4 95 [91 76]
Explanation
A slice is a window onto an underlying array and is the everyday sequence type in Go. []int{82, 91, 76} creates one, len reports its length, and append returns a slice with a value added at the end. You must assign the result, because append may allocate a new array.
scores[1:3] is a sub-slice that includes index 1 and stops before index 3. It shares memory with the original, so changing an element through one is visible through the other.
Explore the dry run
package main import "fmt" func main() { scores := []int{82, 91, 76} scores = append(scores, 95) fmt.Println(len(scores), scores[3]) fmt.Println(scores[1:3])}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create a slice of three ints. | scores = [82 91 76] | — | |
| Append and keep the returned slice. | scores = [82 91 76 95] | — | |
| The length is 4 and index 3 holds 95. | scores = [82 91 76 95] | 4 95 | |
| The window from index 1 up to, but not including, 3. | scores = [82 91 76 95] | 4 95 [91 76] |
Cost and common mistakes
append is amortized O(1); slicing is O(1) because it copies no elements.
- Calling append without assigning the result throws the new slice away.
- Sub-slices share storage with the original; copy them if you need independence.
Try it yourself
What does scores[:2] print for the final slice?
Reveal answer and reasoning
It runs from the start up to index 2, so it prints [82 91].