Collections and Composite Types
Appending to Slices
Slices can grow with append, returning an updated slice value.
append
`append` returns a slice that includes the added value.
Appending to Slices
slices_append.go
Replay: real traced execution (multi-file project)
package main
import "fmt"
func main() {
var nextScore = 95
scores := []int{82, 91}
updated := append(scores, nextScore)
fmt.Println("before=", scores)
fmt.Println("after=", updated)
fmt.Println("length=", len(updated))
}
package main
import "fmt"
func main() {
var nextScore = 70
scores := []int{82, 91}
updated := append(scores, nextScore)
fmt.Println("before=", scores)
fmt.Println("after=", updated)
fmt.Println("length=", len(updated))
}
package main
import "fmt"
func main() {
var nextScore = 100
scores := []int{82, 91}
updated := append(scores, nextScore)
fmt.Println("before=", scores)
fmt.Println("after=", updated)
fmt.Println("length=", len(updated))
}
nextScore ← 95, scores ← []int{82, 91}, updated ← []int{82, 91, 95}
5func main() {6 var nextScore→ 95 = 95 //@nextScore=70, 1007 scores→ []int{82, 91} := []int{82, 91}8 updated→ []int{82, 91, 95} := append(scores[]int{82, 91}, nextScore95)910 fmt.Println("before=", scores[]int{82, 91})11 fmt.Println("after=", updated[]int{82, 91, 95})12 fmt.Println("length=", len(updated[]int{82, 91, 95}))13}outputbefore= [82 91] after= [82 91 95] length= 3
nextScore ← 70, scores ← []int{82, 91}, updated ← []int{82, 91, 70}
5func main() {6 var nextScore→ 70 = 707 scores→ []int{82, 91} := []int{82, 91}8 updated→ []int{82, 91, 70} := append(scores[]int{82, 91}, nextScore70)910 fmt.Println("before=", scores[]int{82, 91})11 fmt.Println("after=", updated[]int{82, 91, 70})12 fmt.Println("length=", len(updated[]int{82, 91, 70}))13}outputbefore= [82 91] after= [82 91 70] length= 3
nextScore ← 100, scores ← []int{82, 91}, updated ← []int{82, 91, 100}
5func main() {6 var nextScore→ 100 = 1007 scores→ []int{82, 91} := []int{82, 91}8 updated→ []int{82, 91, 100} := append(scores[]int{82, 91}, nextScore100)910 fmt.Println("before=", scores[]int{82, 91})11 fmt.Println("after=", updated[]int{82, 91, 100})12 fmt.Println("length=", len(updated[]int{82, 91, 100}))13}outputbefore= [82 91] after= [82 91 100] length= 3
Append One Score
scoresstarts as82, 91.nextScoreis95.append(scores, nextScore)returns an updated slice.- The updated length is
3. | Step | Values | | --- | --- | | before |[82 91]| | appended value |95| | after |[82 91 95]|
Exercise: slices_append.go
Append one score to a slice and print the before slice, after slice, and length