Pointers and Functions
Passing by value vs passing by pointer
Pass by Value
Go passes all function arguments by value — a copy is made. Changes inside the function don't affect the original:
package main
import "fmt"
func increment(n int) { n++ }
func main() {
x := 5
increment(x)
fmt.Println(x) // 5 — unchanged
}Pass by Pointer
Pass a pointer to let the function mutate the original:
package main
import "fmt"
func increment(n *int) { *n++ }
func main() {
x := 5
increment(&x)
fmt.Println(x) // 6
}All lessons in this course
- What Are Pointers?
- Pointers and Functions
- Pointer Receivers on Methods
- new() and When to Use Pointers