Slices
A slice is a window onto an array with a length and a capacity. make creates one. Slicing s[a:b] shares the same memory. append may allocate a new array when capacity runs out. copy duplicates the data.
Example
s := []int{1, 2, 3, 4, 5}
fmt.Println(s[1:4], s[:2], s[3:], len(s), cap(s))
t := make([]int, 0, 10)
t = append(t, 1, 2, 3)
fmt.Println(t, len(t), cap(t))
u := s[:3]
u[0] = 99
fmt.Println(s[0])
v := make([]int, len(u))
copy(v, u)
v[0] = 1
fmt.Println(u[0], v[0])Result
[2 3 4] [1 2] [4 5] 5 5 [1 2 3] 3 10 99 99 1
Exercise
Create a slice with make.
s := ([]int, 3)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.