Course outline
Course / The terminal and the language

Swap two ints

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-02-swap-two-ints
cd 13-02-swap-two-ints
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 Swap so it swaps the values that a and b point to.

Example

x, y := 3, 9
Swap(&x, &y)
fmt.Println(x, y) // 9 3

x, y = 5, 5
Swap(&x, &y)
fmt.Println(x, y) // 5 5

Rules

  • Edit swap.go. The function has a // TODO comment and currently does nothing.
  • Swap the values through the pointers — a and b themselves don't change, but what they point to does.
  • Handle the case where a and b point to the same variable: the value there should be unchanged afterward.
  • Do not change the line func Swap(a, b *int) {. Do not add imports.

What you'll practice

Reading and writing through two pointers in the same function, and keeping a swap correct even when both pointers point to the same place.

Run it

gonomicon fetch week-1/13-02-swap-two-ints
cd 13-02-swap-two-ints
gonomicon test
gonomicon submit

Hints

  1. You can't just write a, b = b, a here — a and b are pointers, so that would swap the pointers themselves, not the values they point to. You need *a and *b.
  2. Save *a somewhere before you overwrite it, the same way you'd swap two cups of water using a third empty cup.
  3. tmp := *a *a = *b *b = tmp

Something wrong with this lesson? Report a problem