Course outline
Course / The terminal and the language

Remember a value after the function returns

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-05-remember-a-value
cd 13-05-remember-a-value
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 Remember so it stores value in a local variable and returns a pointer to that local variable, so the value survives after Remember returns.

Example

p := Remember(5)
fmt.Println(*p) // 5

q := Remember(99)
fmt.Println(*p, *q) // 5 99 -- each call remembers its own value

Rules

  • Edit remember.go. The function has a // TODO comment and currently returns a nil pointer.
  • Do not change the line func Remember(value int) (stored *int) {. Do not add imports.
  • Two separate calls must give back two independent pointers — changing the value through one must never affect the other.

What you'll practice

Returning the address of a local variable so it survives past the end of the function — and watching Go's escape analysis move that variable to the heap to make it safe.

Run it

gonomicon fetch week-1/13-05-remember-a-value
cd 13-05-remember-a-value
gonomicon test
gonomicon submit

Hints

  1. You need a local variable to hold value, and the address of that local variable to return. A parameter is already a local variable, but copying it into its own fresh variable first keeps the two ideas (the copy, and the address you hand back) separate and explicit.
  2. Declare a new local int set to value, point the named result at it with &, and finish with a bare return — the same shape you've used for named results before, just returning an address this time instead of a number.
  3. func Remember(value int) (stored *int) { v := value stored = &v return }

Something wrong with this lesson? Report a problem