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:
| Where | Example | Meaning |
|---|---|---|
| On a type | var p *int | p is a pointer to int |
| In an expression | *p | the 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:
tambahKoin(dompet *int, jumlah int)addsjumlahto the value thatdompetpoints to.tukarSlot(a, b *string)swaps the contents of two weapon slots. After the call,*aholds the old value of*band vice versa.