Course / The terminal and the language
Double through a pointer
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-01-double-through-a-pointer
cd 13-01-double-through-a-pointer
gonomicon submitGoal
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// TODOcomment and currently does nothing. - Use
*nto read and write the valuenpoints to. - If
nisnil, 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
- 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.
- Check n against nil before touching *n — dereferencing a nil pointer panics. If n is nil, just return without doing anything.
- if n == nil { return } *n = *n + *n