Course outline
Course / The terminal and the language

Merge two possibly-nil counters

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-06-merge-two-counters
cd 13-06-merge-two-counters
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 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 // TODO comment and currently returns a nil pointer.
  • a and b may each independently be nil; a nil pointer contributes 0 to the sum.
  • The returned pointer must point to a brand-new variable, not to a or b — changing *a or *b after 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

  1. 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.
  2. 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.
  3. av := 0 if a != nil { av = *a } bv := 0 if b != nil { bv = *b } sum := av + bv return &sum

Something wrong with this lesson? Report a problem