Course / The terminal and the language
Merge two possibly-nil counters
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-06-merge-two-counters
cd 13-06-merge-two-counters
gonomicon submitGoal
Fill in MergeCounters so it returns a new pointer to the sum of a and b, treating either one as 0 when it's nil.
Example
x, y := 5, 7
p := MergeCounters(&x, &y)
fmt.Println(*p) // 12
var missing *int
q := MergeCounters(&x, missing)
fmt.Println(*q) // 5 -- missing counted as 0
r := MergeCounters(missing, missing)
fmt.Println(*r) // 0
Rules
- Edit
merge.go. The function has a// TODOcomment and currently returns a nil pointer. aandbmay each independently benil; anilpointer contributes0to the sum.- The returned pointer must point to a brand-new variable, not to
aorb— changing*aor*bafter the call must never change what the returned pointer points to. - Do not change the line
func MergeCounters(a, b *int) *int {. Do not add imports.
What you'll practice
Guarding two pointers against nil in the same function, combining their values into a new one, and returning the address of that new value so it survives on the heap after the function returns.
Run it
gonomicon fetch week-1/13-06-merge-two-counters
cd 13-06-merge-two-counters
gonomicon test
gonomicon submit
Hints
- Work out each pointer's value on its own first: if it's nil, treat it as 0; otherwise dereference it. Do that for a and for b before you try to add anything together.
- Once you have two plain ints (not pointers), add them and store the sum in a brand-new local variable — then return the address of that variable, the same way you've returned the address of a local before.
- av := 0 if a != nil { av = *a } bv := 0 if b != nil { bv = *b } sum := av + bv return &sum