& and * operators
- Go course
- Beginner
- Lesson 64/90
- 4 min
Learn the address (&) and dereference (*) operators.
The & and * operators
& takes a variable's address; * is used in two senses: in a type, "pointer" (*int), and in an expression, "the value at the address" (*p, dereference).
ad := "Ada"
p := &ad // p's type: *string
fmt.Println(*p) // Ada
*p = "Can"
fmt.Println(ad) // CanThe address itself can be printed with %p (e.g. 0xc000014070); its value changes on every run.
Comparing pointers
When two pointers are compared with ==, their addresses are compared, not their values. To compare the values, dereference first:
a, b := 5, 5
pa, pb := &a, &b
fmt.Println(pa == pb) // false: different variables
fmt.Println(*pa == *pb) // true: same valuePractice Two pointers
Declare a := 1. Take p := &a and q := p, then set *q = 7. Print the value of a and the result of p == q on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
a := 1
p := &a
q := p
*q = 7
fmt.Println(a, p == q)
}Expected output
7 true
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 After <code>a := 1; p := &a; q := p; *q = 7</code>, what is <code>a</code>?
- 7 Correct answer
- 1
- 0
- An error
Explanation: q := p copies the address; p and q point to the same a. *q = 7 changes a.
2 Take the address
sayi := 42
p := ____sayi
sayi := 42
p := &sayi
Explanation: The & operator gives the variable's address.
3 Code and result (a, b := 5, 5)
| Term | Meaning |
|---|---|
&a == &a |
true |
&a == &b |
false |
*(&a) |
5 |
p := &a; *p = 9 |
a = 9 |