Course outline
Course / The terminal and the language

Double through a pointer

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-01-double-through-a-pointer
cd 13-01-double-through-a-pointer
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 DoubleThroughPointer so it doubles the int that n points to, writing the result back through the pointer — and does nothing if n is nil.

Example

value := 7
DoubleThroughPointer(&value)
fmt.Println(value) // 14

value = -3
DoubleThroughPointer(&value)
fmt.Println(value) // -6

var missing *int
DoubleThroughPointer(missing) // does nothing, does not panic

Rules

  • Edit double.go. The function has a // TODO comment and currently does nothing.
  • Use *n to read and write the value n points to.
  • If n is nil, the function should do nothing: no panic, no change to anything.
  • Do not change the line func DoubleThroughPointer(n *int) {. Do not add imports.

What you'll practice

Dereferencing a pointer to read and write a value, writing into a caller's variable through a pointer parameter, and checking a pointer against nil before using it.

Run it

gonomicon fetch week-1/13-01-double-through-a-pointer
cd 13-01-double-through-a-pointer
gonomicon test
gonomicon submit

Hints

  1. n is a *int, so you reach the value it points to with *n. Doubling means adding that value to itself, or multiplying it by 2.
  2. Check n against nil before touching *n — dereferencing a nil pointer panics. If n is nil, just return without doing anything.
  3. if n == nil { return } *n = *n + *n

Something wrong with this lesson? Report a problem