0PricingLogin
Go Academy · Lesson

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

  1. What Are Pointers?
  2. Pointers and Functions
  3. Pointer Receivers on Methods
  4. new() and When to Use Pointers
← Back to Go Academy