Pointers and functions
- Go course
- Beginner
- Lesson 66/90
- 4 min
Learn to pass pointers to functions and modify values.
Pointers and functions
Go copies every argument. For a function to change the caller's variable, its address is passed:
func ikiKat(n *int) {
*n *= 2
}
x := 5
ikiKat(&x)
fmt.Println(x) // 10Seeing *int in a function signature means "this function may change the value"; it is an important hint for the reader.
Return a value or take a pointer?
In most cases returning the new value is more readable: x = ikiKat(x). A pointer parameter makes sense when updating many fields of a struct in place or filling several outputs. fmt.Sscan(&a, &b) and json.Unmarshal(data, &v) are examples of standard functions that take pointers.
Practice Swap
Write the degistir(a, b *int) function. For x, y := 1, 2, call degistir(&x, &y) and print x and y.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func degistir(a, b *int) {
*a, *b = *b, *a
}
func main() {
x, y := 1, 2
degistir(&x, &y)
fmt.Println(x, y)
}Expected output
2 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What should the signature of a function that swaps two variables be?
- func degistir(a int, b *int)
- func degistir() (int, int)
- func degistir(a, b *int) Correct answer
- func degistir(a, b int)
Explanation: To change both variables, both addresses are needed; inside, write *a, *b = *b, *a.
2 Pass the address
x := 5
ikiKat(____x)
fmt.Println(x) // 10
x := 5
ikiKat(&x)
fmt.Println(x) // 10
Explanation: Since the function expects *int, x's address is passed with &x.
3 Signature and meaning
| Term | Meaning |
|---|---|
func f(n int) |
Takes a copy |
func f(n *int) |
Can change it |
f(&x) |
Address is passed |
json.Unmarshal(b, &v) |
Fills the target |