×

go · level 2 · unit 1 · lesson 1

  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

A looks values up by name, like a café price list.

A slice finds items by their position number. Often you would rather look things up by name: how much is the tea? A map stores values under keys, like a café price list where every drink sits next to its price.

prices := map[string]int{"tea": 2, "cake": 3} makes a map. [string] says the keys are strings and int says the values are whole numbers. A colon joins each to its value, and commas separate the pairs.

Read a value by putting its key in square brackets: prices["cake"] gives 3. fmt.Println(prices) shows the whole map, with the keys in A to Z order.

package main
import "fmt"
func main() {
	prices := map[string]int{"tea": 2, "cake": 3, "toast": 1}
	fmt.Println(prices["cake"])
	fmt.Println(prices)
}

Keys are often strings, but other types work too, so map[int]string uses whole numbers as keys.