Lesson 1 · Unit 04
Slices
Indexes, len, append, range, slicing, and two names that share one row of values.
What you practise
- Arrays against slices, indexes from 0,
len,append, slicing,range, two slices sharing one array
Try a question from this lesson
Pick one
A slice holds several values under one name. Positions count from 0, as they do in a string. What does this print?
scores := []int{70, 85, 90}
fmt.Println(scores[0], len(scores))Correct answer
70 3
Why
[]int{70, 85, 90} is a slice of three ints. Position 0 is the first one, 70, and len counts the values: 3. The positions are called indexes, and here they run from 0 to 2.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Slices
A slice is a row of values of one type. []int{4, 8, 15} is a slice of ints, and []string{"a", "b"} is a slice of strings.
s[i] reads the value at index i, and s[i] = x replaces it. len(s) is how many values there are, so the last index is len(s)-1.
nums := []int{4, 8, 15}
nums[0] = 5
fmt.Println(nums[0], nums[2]) // 5 15
fmt.Println(nums) // [5 8 15]Concept
append and range
append adds a value to the end of a slice and hands back the longer slice. You must keep what it returns: s = append(s, x).
range walks through a slice for you. On each pass it gives the index and the value. If you do not need one of them, put _ in its place.
var list []string // an empty slice
list = append(list, "tea")
list = append(list, "milk")
for i, item := range list {
fmt.Println(i, item)
}
// 0 tea
// 1 milkConcept
Slicing, sharing and arrays
s[1:3] is a slice of a slice: from index 1 up to, but not including, index 3. Leave a side out to mean "from the start" or "to the end".
It is a window onto the same values, not a copy. So is b := a for a slice: change a value through one name and the other sees it.
An array, written with a size like [3]int, has a fixed length and is copied when assigned.
a := []int{10, 20, 30, 40}
mid := a[1:3] // 20 30
mid[0] = 99
fmt.Println(a) // [10 99 30 40]
fmt.Println(mid) // [99 30]9 more exercises in the app
- 3× type the answer
- 3× multiple choice
- 1× order the lines
- 1× fill the blanks
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.