go · level 2 · unit 1 · lesson 1
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
Three friends, three ages. 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() {
ages := map[string]int{"Zara": 9, "Ali": 11, "Mo": 10}
fmt.Println(ages)
}
your turn
Your turn. Write your own snack menu.
Put two snacks of your own on the menu, each with a whole-number price above 0. Then type one of those snacks in the choice blank, spelled exactly the same, and run it.
output
press run to see what happens
fix it
The café cannot find the cake. Can you fix it?
output
press run to see what happens
- Read the error. Go says
pricesis not a function, so why does it think you are calling one? - Round brackets call a function. To look up a key in a map, you need a different kind of bracket.
- Change prices("cake") to prices["cake"] with square brackets, then run.
nailed it
you built your first map. :D
- A map stores values under keys.
map[string]inthas string keys and whole-number values.- Look a value up with its key in square brackets.
new words in your collection
- map
- key
This lesson isn’t saved. A free account remembers every lesson you finish.