Course outline
Course / The terminal and the language

Read a pointer, or fall back

Lab

How to fetch and submit this lab

Once: install the tool and connect your account.

curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon login

Each lab: download it, edit the file named in the instructions, then submit.

gonomicon fetch week-1/13-03-read-or-fallback
cd 13-03-read-or-fallback
gonomicon submit

Go installed? gonomicon test runs the visible test on your computer first. Submitting also runs hidden checks on our server.

Goal

Fill in ReadOrFallback so it returns the value p points to, or fallback when p is nil.

Example

x := 7
fmt.Println(ReadOrFallback(&x, -1)) // 7

var missing *int
fmt.Println(ReadOrFallback(missing, -1)) // -1

Rules

  • Edit readorfallback.go. The function has a // TODO comment and a return line you will change.
  • Check p against nil before dereferencing it.
  • p pointing at 0 is not the same thing as p being nil — a pointer to 0 is still a real pointer, and should return 0, not fallback.
  • Do not change the line func ReadOrFallback(p *int, fallback int) int {. Do not add imports.

What you'll practice

Guarding a pointer with a nil check before dereferencing it, and telling "no value" (nil) apart from "a value that happens to be zero."

Run it

gonomicon fetch week-1/13-03-read-or-fallback
cd 13-03-read-or-fallback
gonomicon test
gonomicon submit

Hints

  1. Start by checking p against nil, the same way you'd guard any pointer before dereferencing it.
  2. When p is nil there's nothing to read, so return fallback right away with an early return. Otherwise dereference p and return that.
  3. if p == nil { return fallback } return *p

Something wrong with this lesson? Report a problem