CodingNeed.

2 · Model and validate · 25 MIN

Structs, maps and missing values

A map lookup can distinguish a missing key from a stored zero.

Structs describe named fields, while maps index records by a comparable key. The two-value lookup returns both a value and a presence flag. Without that flag, a learner who has earned zero points can look identical to a learner who does not exist. This example deliberately includes a zero value. Reading a nil map works, but writing to it panics, so initialize maps before mutation. Map iteration order is unspecified; sort keys when you need deterministic output for reports or tests.

Use value, ok := records[id] and test ok before reading business fields.

Read the example

package main
import "fmt"
type Learner struct { Name string; Points int }
func main() {
  learners := map[string]Learner{"ada": {Name:"Ada", Points:0}}
  learner, found := learners["ada"]
  fmt.Println(learner.Name, learner.Points, found)
  _, missing := learners["lin"]
  fmt.Println(missing)
}
Check the expected output
Ada 0 true
false

Your challenge

Write a lookup function that returns a learner and an error for an unknown ID.

Solution cost: Expected O(1) lookup; sorted reporting adds O(k log k). time · Account for collection storage separately from the returned result. space

Common trap

Do not infer existence from the zero value of a field.

Study the project implementation
package main
import "fmt"
type Learner struct { Name string; Points int }
func main() {
  learners := map[string]Learner{"ada": {Name:"Ada", Points:0}}
  learner, found := learners["ada"]
  fmt.Println(learner.Name, learner.Points, found)
  _, missing := learners["lin"]
  fmt.Println(missing)
}

Further reading: Official documentation

Next lesson: Errors and input boundaries

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.