go · level 1 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Every item has a number, starting from 0.
Each item has a position number called its . Go starts counting at 0, so snacks[0] is the first item and snacks[1] is the second. The last one is snacks[len(snacks)-1].
Change an item by putting a new value at its index: snacks[1] = "pear". Ask for an index that does not exist, and the program crashes with a .
adds an item to the end. It hands back a longer slice, so store it: snacks = append(snacks, "grapes").
package main
import "fmt"
func main() {
snacks := []string{"crisps", "apple", "cake"}
fmt.Println(snacks[0])
snacks[1] = "pear"
snacks = append(snacks, "grapes")
fmt.Println(snacks)
fmt.Println(snacks[len(snacks)-1])
} A panic happens while the program runs, so lines before it still show their output.
guess first
Swap one, add one. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
package main
import "fmt"
func main() {
pets := []string{"cat", "dog", "fish"}
pets[0] = "hamster"
pets = append(pets, "parrot")
fmt.Println(pets[0], len(pets))
}
your turn
Your turn. Join the queue.
Type your own name to join the end of the queue. Index 2 is the third item, which is you.
output
press run to see what happens
fix it
This program panics. Can you fix it?
output
press run to see what happens
- There are 3 colours. What index does the first one have?
- Counting starts at 0, so the indexes are 0, 1 and 2. There is no index 3.
- Change colours[3] to colours[2], then press run.
nailed it
you can reach into a slice now. :D
- Indexes start at 0, so the first item is
[0]. s = append(s, item)adds an item to the end.- A missing index makes the program panic.
new words in your collection
- index
- panic
- append
This lesson isn’t saved. A free account remembers every lesson you finish.