Course / The terminal and the language
Swap two ints
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-02-swap-two-ints
cd 13-02-swap-two-ints
gonomicon submitGoal
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// TODOcomment and currently does nothing. - Swap the values through the pointers —
aandbthemselves don't change, but what they point to does. - Handle the case where
aandbpoint 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
- 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.
- Save *a somewhere before you overwrite it, the same way you'd swap two cups of water using a third empty cup.
- tmp := *a *a = *b *b = tmp