Course / The terminal and the language
Read a pointer, or fall back
How to fetch and submit this lab
Once: install the tool and connect your account.
curl -fsSL https://gonomicon.com/install.sh | sh
gonomicon loginEach 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 submitGoal
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// TODOcomment and a return line you will change. - Check
pagainstnilbefore dereferencing it. ppointing at0is not the same thing aspbeingnil— a pointer to0is still a real pointer, and should return0, notfallback.- 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
- Start by checking p against nil, the same way you'd guard any pointer before dereferencing it.
- When p is nil there's nothing to read, so return fallback right away with an early return. Otherwise dereference p and return that.
- if p == nil { return fallback } return *p