Lesson 2 · Unit 01
Slices and maps
Arrays copy, slices share, append may move, maps answer twice.
What you practise
- Arrays against slices,
lenandcap,appendand the shared backing array,range, maps and the comma-ok lookup
Try a question from this lesson
Pick one
In Python, b = a gives one list two names. Here a is a Go array of three ints. What prints?
a := [3]int{1, 2, 3}
b := a
b[0] = 99
fmt.Println(a[0], b[0])Correct answer
1 99
Why
An array is a value: b := a copies all three elements, so changing b leaves a alone. The length is part of the type [3]int and an array can never grow, which is why you will mostly use slices instead.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
A slice is a window
[3]int is an array: a fixed block of values. []int, with no length, is a slice: a small header holding a pointer into an array, a length and a capacity.
Copying a slice copies the header, not the elements, so both copies see the same array. That is the behaviour you know from Python lists.
nums[1:3] builds a new header onto the same array, covering elements 1 and 2.
nums := []int{10, 20, 30, 40}
mid := nums[1:3]
mid[0] = 99
fmt.Println(nums, mid)
// [10 99 30 40] [99 30]Concept
append may or may not copy
append(s, x) returns a slice with x on the end. If the array underneath has spare capacity, the element is written there and the result shares the array with s. If it is full, Go first copies everything to a bigger array.
So always keep the result: s = append(s, x). And take care when appending to a slice that someone else still holds: you may be writing into their array.
a := make([]int, 2, 4) // len 2, cap 4
b := append(a, 5) // fits: shared
b[0] = 9
fmt.Println(a[0], len(a), len(b))
// 9 2 310 more exercises in the app
- 4× type the answer
- 2× multiple choice
- 1× fill the blanks
- 1× true or false
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.