Thuta Learning
Go
AdvancedProgrammingBeginner

Pointers

GoLesson 1625 min

What you'll walk away with

  • Take an address with &x and read or write through it with *p
  • Explain that Go copies every argument and what changes when you pass a pointer
  • Understand why returning the address of a local variable is safe (escape analysis)
  • Avoid nil-pointer-dereference panics and the range-loop copy trap

Explain it simply

Explain it simply

Picture a variable as a house and its value as the things inside. A pointer is a slip of paper with the house's address on it. Give a friend a copy of your things and whatever they change does not touch your house; give them the address and they can walk in and really change what is there.

In Go, &brand means "give me the address of brand", and *name means "go inside the house at this address". The type *string reads as "the address of a string".

Problem → Why → Solution

The problem: the change inside the function is lost

An HR app has an applyRaise() function that gives an employee a 10% raise. Printing inside the function shows the new salary, yet back in main() the salary is unchanged. There is no compile error and no warning, so this bug can easily reach production.

raise.go
type Employee struct {
    Name   string
    Salary int
}

func applyRaise(e Employee) {   // e is a copy of the caller's struct
    e.Salary = e.Salary * 110 / 100
    fmt.Println("inside:", e.Salary) // 550000
}

func main() {
    aye := Employee{Name: "Aye", Salary: 500000}
    applyRaise(aye)
    fmt.Println("after:", aye.Salary) // still 500000
}

Why is the raise lost?

Go passes every argument by value, copying it. Calling applyRaise(aye) copies the whole struct into e, so changing e.Salary only changes the copy. Make the function take a pointer, func applyRaise(e *Employee), and call applyRaise(&aye): now only the address is copied, and the function can change aye itself.

Core concept: addresses, dereferencing and pass by value

Pointers need only two operators. &x gives the address of variable x; if x is an int, the result has type *int. *p dereferences: it reads the value p points to (fmt.Println(*p)) or writes it (*p = 95). The * symbol means "pointer type" inside a type (*int) and "the value pointed to" inside an expression (*p).

The zero value of every pointer type is nil, meaning it points at nothing. Dereferencing a nil pointer makes the program panic, so check any pointer that might be nil before using it. There are two ways to get a new pointer: new(int) allocates a zero int and returns its address, while for structs the composite-literal form &Employee{Name: "Aye"} is far more common. Through a struct pointer p you can write p.Name directly, because Go rewrites it as (*p).Name for you.

The rule that Go copies every argument has no exceptions; passing a pointer copies the address. But both copies point at the same value, so changes made inside the function are visible to the caller. Two pointers referring to one value is called aliasing, and it can make it hard to trace where a change came from, so use it deliberately.

In C, returning the address of a local variable is dangerous; in Go it is safe. The compiler's escape analysis notices that the value is still used after the function returns, moves it to the heap, and the garbage collector frees it once nothing refers to it (go build -gcflags=-m shows these compiler decisions). Go also has no pointer arithmetic such as p++, which removes whole classes of bugs like reading past the end of an array or scribbling over unrelated memory. The unsafe package can bypass these rules, but ordinary application code does not use it.

text
updateName(&brand)
------------------
main()                        updateName()
+--------------------+        +------------------------+
| brand: "Old Name"  | <----- | name: *string (address |
| (address 0xc000..) |        |       of brand)        |
+--------------------+        +------------------------+
*name = "ThutaTech" writes into brand itself, not into a copy
Mental model: copy the address, share the value
  1. &brand takes the address
  2. The function gets a copy of it
  3. *name reads or writes brand itself
  4. Back in main, the change is visible

Something is always copied; the only question is whether it is the value or the address.

General pattern

go
var p *Type          // nil until it points somewhere
p = &variable        // address of an existing variable
p = &Type{Field: v}  // address of a new struct value
q := new(Type)       // address of a new zero value

value := *p          // read through the pointer
*p = newValue        // write through the pointer
p.Field = v          // struct field: same as (*p).Field = v

func change(x *Type) { *x = newValue } // call as change(&variable)

In a type position *Type is a pointer type; in an expression *p is a dereference. When a function must change the caller's value, declare the parameter as *Type and call it with &variable.

Example: renaming a brand through a pointer

This example shows the whole basic pointer pattern in a few lines: a *string parameter, &brand at the call site and *name = ... inside the function. updateName returns nothing, yet brand in main() changes.

go
package main

import "fmt"

func updateName(name *string) {
    *name = "ThutaTech"
}

func main() {
    brand := "Old Name"
    updateName(&brand)
    fmt.Println(brand)
}

Code breakdown

  1. Parameterfunc updateName(name *string) {

    name has type *string: it receives the address of a string. Passing a plain string value here is a compile error.

  2. Write through*name = "ThutaTech"

    Dereferences and replaces the string stored at that address. Writing name = ... without the * would only repoint the local pointer and never reach the caller.

  3. Variablebrand := "Old Name"

    An ordinary, addressable variable. Escape analysis decides whether it lives on the stack or the heap; you do not have to manage that.

  4. Pass addressupdateName(&brand)

    &brand produces brand's address, and a copy of that address lands in name.

  5. Resultfmt.Println(brand)

    updateName changed brand itself, so this prints "ThutaTech".

You should see
ThutaTech

The pointer basics in one program

The program below shows reading, writing, copying a pointer, the nil zero value and new() together. q := p copies the address, not the int, so *q += 5 changes score.

basics.go
package main

import "fmt"

func main() {
    score := 70
    p := &score // p has type *int and holds the address of score

    fmt.Println("via pointer:", *p)
    *p = 95 // write through the pointer
    fmt.Println("score is now:", score)

    q := p // copy the pointer, not the int
    *q += 5
    fmt.Println("both see:", *p, score)

    var none *int
    fmt.Println("zero value is nil:", none == nil)

    n := new(int) // pointer to a fresh zero int
    fmt.Println("new(int) points to:", *n)
}

The output is "via pointer: 70", "score is now: 95", "both see: 100 100", "zero value is nil: true" and "new(int) points to: 0".

Returning a local's address, and aliasing

NewCounter() returns the address of its local struct c. Escape analysis has moved c to the heap, so the pointer stays valid after the function returns; every Go constructor function relies on this. alias := visits makes two pointers share one struct, while *visits copies the whole struct.

escape.go
package main

import "fmt"

type Counter struct {
    Name  string
    Count int
}

// Returning the address of a local is safe in Go:
// escape analysis moves c to the heap.
func NewCounter(name string) *Counter {
    c := Counter{Name: name}
    return &c
}

func main() {
    visits := NewCounter("visits")
    visits.Count++ // same as (*visits).Count++
    visits.Count++
    fmt.Println(visits.Name, visits.Count)

    alias := visits
    alias.Count = 10
    fmt.Println("visits sees alias's change:", visits.Count)

    copyOf := *visits // dereference = copy the whole struct
    copyOf.Count = 99
    fmt.Println("copy is independent:", visits.Count, copyOf.Count)
}

The output is "visits 2", "visits sees alias's change: 10" and "copy is independent: 10 99".

In real projects

Where this shows up in real projects

In real Go code pointers show up in three main places. First, constructor functions such as NewServer(cfg Config) *Server. Second, pointer-receiver methods that change state. Third, APIs that say "fill this variable for me", such as json.Unmarshal(data, &user); forget the & there and Unmarshal refuses the non-pointer argument and returns an error.

Pointers also distinguish "no value" from "zero value" in database rows or JSON: with MiddleName *string, nil means "not provided" while "" means "provided as empty". Be careful with performance assumptions, though. Copying ints and small structs is very fast, while pointers can cause heap allocations and more garbage-collector work. "Pointers are always faster" is often false, so choose a pointer when you need mutation, when the struct is genuinely large, or when state must be shared, and measure with a benchmark.

Common mistakes

Common mistakes

1. Dereferencing a nil pointer

var u *User; fmt.Println(u.Name) stops the program with "panic: runtime error: invalid memory address or nil pointer dereference". Check pointers that can be nil, such as results of lookups or find functions, with if u == nil first, or design the function to also return a bool or an error.

2. Changing the range variable and expecting the slice to change

In for _, t := range tasks { t.Done = true }, t is a copy of each element, so the tasks in the slice never change. Update through the index, for i := range tasks { tasks[i].Done = true }, or take the element's address with p := &tasks[i].

3. Keeping a pointer to a slice element across append

If you take p := &tasks[0] and then tasks = append(tasks, newTask), append copies everything into a new array when capacity runs out. After that, p.Done = true changes the old array and tasks[0] never shows it. Take the pointer again after appending, or store []*Task instead.

rangecopy.go
package main

import "fmt"

type Task struct {
    Title string
    Done  bool
}

func main() {
    tasks := []Task{{Title: "write"}, {Title: "test"}}

    for _, t := range tasks {
        t.Done = true // changes a copy only
    }
    fmt.Println("range copy:", tasks[0].Done, tasks[1].Done) // false false

    for i := range tasks {
        tasks[i].Done = true // changes the element in the slice
    }
    fmt.Println("by index:  ", tasks[0].Done, tasks[1].Done) // true true
}

Mini challenge

Mini challenge: find a task and update it through a pointer

Write a function that finds a task by ID and returns a pointer to the element inside the slice. Return nil when nothing matches, and handle that nil safely.

  • findTask(tasks []Task, id int) *Task returns &tasks[i] (not the address of a range variable)
  • markDone(t *Task) bool returns false for a nil t instead of panicking
  • rename(t *Task, title string) does nothing for a nil t
  • Finally print every task to show the changes reached the slice
tasks.go
package main

import "fmt"

type Task struct {
    ID    int
    Title string
    Done  bool
}

func findTask(tasks []Task, id int) *Task {
    // TODO: loop by index and return the address of the matching element
    return nil
}

func markDone(t *Task) bool {
    // TODO: guard against nil, then set Done
    return false
}

// TODO: rename(t *Task, title string)

func main() {
    tasks := []Task{{ID: 1, Title: "plan"}, {ID: 2, Title: "code"}}
    // TODO: mark 2 and 7 done, rename 1 and 9, then print every task
    fmt.Println(findTask(tasks, 1), markDone(nil))
}

Expected: The program prints: mark 2: true mark 7: false 1 plan sprint done=false 2 code done=true

Show hint

for _, t := range tasks { if t.ID == id { return &t } } returns the address of a copy, which is wrong. Loop with for i := range tasks and return &tasks[i]. To print aligned columns use fmt.Printf("%d %-12s done=%v\n", ...).

Show solution
tasks.go
package main

import "fmt"

type Task struct {
    ID    int
    Title string
    Done  bool
}

// findTask returns a pointer into the slice, or nil if no task matches.
func findTask(tasks []Task, id int) *Task {
    for i := range tasks {
        if tasks[i].ID == id {
            return &tasks[i]
        }
    }
    return nil
}

func markDone(t *Task) bool {
    if t == nil {
        return false
    }
    t.Done = true
    return true
}

func rename(t *Task, title string) {
    if t != nil {
        t.Title = title
    }
}

func main() {
    tasks := []Task{{ID: 1, Title: "plan"}, {ID: 2, Title: "code"}}

    fmt.Println("mark 2:", markDone(findTask(tasks, 2)))
    fmt.Println("mark 7:", markDone(findTask(tasks, 7)))
    rename(findTask(tasks, 1), "plan sprint")
    rename(findTask(tasks, 9), "ignored")

    for _, t := range tasks {
        fmt.Printf("%d %-12s done=%v\n", t.ID, t.Title, t.Done)
    }
}

Quick quiz 1 / 3

After x := 5; p := &x; *p = *p * 2; q := p; *q++, what is x?

Quick quiz 2 / 3

Which statement about func newUser() *User { u := User{Name: "Aye"}; return &u } is true?

Quick quiz 3 / 3

Which loop actually sets Done = true on the tasks stored in the slice tasks?

What to remember

  • &x gives an address, *p reads or writes the value it points to, and a pointer's zero value is nil.
  • Go copies every argument; passing a pointer copies the address, so the function can change the original.
  • Returning a local's address is safe thanks to escape analysis, and Go has no pointer arithmetic.
  • Check pointers that may be nil, and change slice elements by index because the range variable is a copy.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Pointers | Thuta Learning