Maps store values by key, which makes lookup code direct.

map lookup A map lookup such as `scores[key]` returns the value stored for that key.

Maps

key
maps_intro.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var key = "go"
	scores := map[string]int{
		"go":     95,
		"ruby":   88,
		"python": 92,
	}
	value := scores[key]

	fmt.Println("key=", key)
	fmt.Println("value=", value)
}
package main

import "fmt"

func main() {
	var key = "ruby"
	scores := map[string]int{
		"go":     95,
		"ruby":   88,
		"python": 92,
	}
	value := scores[key]

	fmt.Println("key=", key)
	fmt.Println("value=", value)
}
package main

import "fmt"

func main() {
	var key = "python"
	scores := map[string]int{
		"go":     95,
		"ruby":   88,
		"python": 92,
	}
	value := scores[key]

	fmt.Println("key=", key)
	fmt.Println("value=", value)
}
  1. key ← "go", scores ← map[string]int{"go":95, "python":92, "ruby":88}

    5func main() {6  var key→ "go" = "go" //@key="ruby", "python"7  scores→ map[string]int{"go":95, "python":92, "ruby":88} := map[string]int{8    "go":     95,9    "ruby":   88,10    "python": 92,11  }12  value→ 95 := scores[key]951314  fmt.Println("key=", key"go")15  fmt.Println("value=", value95)16}
    outputkey= go
    value= 95
  1. key ← "ruby", scores ← map[string]int{"go":95, "python":92, "ruby":88}

    5func main() {6  var key→ "ruby" = "ruby"7  scores→ map[string]int{"go":95, "python":92, "ruby":88} := map[string]int{8    "go":     95,9    "ruby":   88,10    "python": 92,11  }12  value→ 88 := scores[key]881314  fmt.Println("key=", key"ruby")15  fmt.Println("value=", value88)16}
    outputkey= ruby
    value= 88
  1. key ← "python", scores ← map[string]int{"go":95, "python":92, "ruby":88}

    5func main() {6  var key→ "python" = "python"7  scores→ map[string]int{"go":95, "python":92, "ruby":88} := map[string]int{8    "go":     95,9    "ruby":   88,10    "python": 92,11  }12  value→ 92 := scores[key]921314  fmt.Println("key=", key"python")15  fmt.Println("value=", value92)16}
    outputkey= python
    value= 92

Look Up a Score

  1. The map stores scores by language name.
  2. key is go.
  3. scores[key] reads the value for that key.
  4. The printed value is 95. | Key | Score | | --- | --- | | go | 95 | | ruby | 88 | | python | 92 |

Exercise: maps_intro.go

Look up one score by map key and print the key and value