Go course

PointersAddress and Dereference: & and *

Go

Display

Theme

Pointers · Test exercise

Address and Dereference: & and *

Every variable is stored at some location in memory. A pointer is a value that holds the address of that location.

koin := 50
p := &koin       // & = "ambil alamat dari"

fmt.Println(p)   // 0xc000012345 (alamat, bisa berbeda-beda)
fmt.Println(*p)  // 50 — * = "ambil nilai di alamat ini"

Read & as "take the address of" and * as "take the value at this address". The address you see printed may differ from run to run. The type of p is *int, read as "pointer to int". The * sign has two roles:

WhereExampleMeaning
On a typevar p *intp is a pointer to int
In an expression*pthe value p points to (dereference)

Changing a value through a pointer

A dereference can also go on the left side of an assignment. That way we change the original variable:

*p = 80
fmt.Println(koin) // 80 — koin ikut berubah karena p menunjuk ke koin
*p += 5
fmt.Println(koin) // 85

koin changes too, because p points to it. Two pointers that point to the same variable always "see" the same value:

q := p
*q = 0
fmt.Println(koin, *p) // 0 0

Pointers as parameters

This is what pointers are for: a function can change a variable that belongs to its caller.

func reset(n *int) {
	*n = 0
}

nyawa := 3
reset(&nyawa)
fmt.Println(nyawa) // 0

Task

In an arcade game, complete the following two functions:

  1. tambahKoin(dompet *int, jumlah int) adds jumlah to the value that dompet points to.
  2. tukarSlot(a, b *string) swaps the contents of two weapon slots. After the call, *a holds the old value of *b and vice versa.
main.go
package main

import "fmt"

func tambahKoin(dompet *int, jumlah int) {
	// TODO: tambahkan jumlah ke nilai yang ditunjuk dompet
}

func tukarSlot(a, b *string) {
	// TODO: tukar isi *a dan *b
}

func main() {
	koin := 10
	tambahKoin(&koin, 5)
	fmt.Println("Koin:", koin)

	kiri, kanan := "pedang", "busur"
	tukarSlot(&kiri, &kanan)
	fmt.Println("Kiri:", kiri, "Kanan:", kanan)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)