×

go · level 1 · unit 6 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.