Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 147 ยท Pointers and Memory

Pointers

Learn Go pointers from scratch - the & and * operators, nil pointers and panics, pointers to structs, comparing pointers, new(T) and new(expr) in Go 1.26, and when to use them.

Every variable in a running program lives somewhere in memory, and that place has an address. A pointer is a value that holds such an address. Instead of passing around a copy of some data, you can pass around the location of the data, and whoever receives the pointer can read or change the original.

Go has pointers, but they are much tamer than the ones in C. There is no pointer arithmetic, memory is freed automatically by the garbage collector, and you rarely have to think about where a value is stored. What remains is the useful part: sharing and modifying data through a reference. This lesson covers the two pointer operators, nil, pointers to structs, pointer comparison, new, and guidelines for when a pointer is the right tool. The next lesson, Pointers, Values and Functions, applies all this to function calls.

The & and * operators

Two operators do all the work:

  • &x produces a pointer to the variable x (read it as "address of x").
  • *p follows the pointer p to the variable it points to (read it as "the value at p"). This is called dereferencing.

The type of a pointer to an int is written *int. A pointer to a string is *string, and so on. The same * symbol appears in the type and in the dereference expression, but the context makes the meaning clear.

Go Taking an address and following it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Both n and *p name the same variable. Changing one changes the other. That is the whole idea of a pointer: two names, one piece of data.

You can only take the address of something that is addressable: a variable, a field of an addressable struct, an element of a slice, or an element of an addressable array. You cannot write &10 or &f(). Composite literals are a special case: &Point{1, 2} is allowed and creates a new value.

Pointers are values too

A pointer variable is a normal variable. You can copy it, store it in a slice or a struct, and pass it to a function. Copying a pointer copies the address, not the data it points to, so both copies still refer to the same variable.

Go Two pointers, one variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

nil pointers

The zero value of every pointer type is nil, which means "points at nothing". A nil pointer is perfectly valid to hold, copy and compare, but dereferencing it crashes the program with a runtime panic.

Go Dereferencing nil (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The run prints panic: runtime error: invalid memory address or nil pointer dereference, followed by [signal SIGSEGV: segmentation violation ...] and a stack trace that names the line that did the dereference. Exit code 2.

The defense is simple: check before you dereference whenever a pointer can legitimately be nil.

Go Guarding against nil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Pointers are the classic way to represent an optional value: nil means "absent", anything else means "present". Be careful with that pattern for plain numbers, though, because every use must check for nil.

Pointers to structs

Structs are where pointers appear most. Writing (*p).Name to reach a field would be tiresome, so Go lets you write p.Name and dereferences automatically:

Go Automatic dereference for fields

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice that fmt prints a pointer to a struct as &{Ada 8}, but a pointer to anything else (like *int) as a raw hexadecimal address. Method calls get the same convenience, which you will see in Methods.

Comparing pointers

Two pointers are equal if they point to the same variable (or both are nil). Equality does not look at the contents.

Go Pointer equality is identity

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Pointers can be used as map keys for the same reason: the key is the identity of the variable, not what it holds. Only == and != are allowed; there is no < for pointers.

No pointer arithmetic

In C you can write p + 1 to step to the next element. Go does not allow this. You cannot add to a pointer, subtract two pointers, or turn an integer into a pointer. To step through data you use slices and indexes, which are bounds-checked. This removes a whole family of memory-corruption bugs. (The unsafe package exists for the rare cases that need more, and it is deliberately named that way.)

Creating pointers with new

The built-in new(T) allocates a fresh variable of type T, set to its zero value, and returns a pointer to it:

Go new allocates a zeroed variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

new with an expression (Go 1.26)

Before Go 1.26, getting a pointer to a literal value needed two steps: declare a variable, then take its address. Starting with Go 1.26, the operand of new can be an expression, and the result points to a new variable initialized with that value:

Go new(expr) in Go 1.26 and later

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

This is handy for optional fields in structs, which is common in JSON models and API request types. Programs using new(expr) need a go directive of 1.26 or later in go.mod. The make, new and composite literals lesson compares all the ways to create values.

Pointers to pointers and to arrays

Because a pointer is a value, you can take its address too. A **int ("pointer to pointer to int") needs two dereferences: *pp is the inner pointer and **pp is the integer. The main practical use is a function that must change which variable a pointer points to, not just the value it points at:

Go Double pointers and pointers to arrays

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go lets you index, slice, range over and take the len of a pointer to an array without writing the explicit dereference. For anything but a fixed-size array you normally pass a slice instead (Slices), which already shares its backing array. len and cap of a pointer to an int are not defined: a pointer has no length, only an array (or slice) does.

Why pointers exist

Go passes everything by value: arguments, receivers and assignments all copy. Without pointers, a function could never change the caller's variable, and every large value would be copied on every call. A pointer solves three problems: mutation (change the original), cost (copy 8 bytes instead of a large struct) and identity (several parts of a program refer to one shared object). The price is that your code must now reason about aliasing and nil.

When to use a pointer

Pointers are a tool, not a default. Good reasons to use one:

  • The function or method must modify the caller's value. Passing &x lets the callee change x.
  • The value is large, and copying it on every call would be wasteful. Copying a struct with several fields is cheap, but an array with a million elements is not.
  • The value must be shared or have identity: a node in a linked list, a single database connection, a mutex that must not be copied.
  • You need "absent": nil means no value.

Reasons not to reach for a pointer:

  • For small values like int, float64, string, or small structs, a copy is as fast or faster, and avoids a nil check.
  • Slices, maps, channels and functions already contain references internally, so you rarely need a pointer to them. The next lesson explains why.
  • Extra pointers mean extra work for the garbage collector, as you will see in Stack, Heap and Escape Analysis.

A good default: start with values. Add a pointer when you can name the reason, such as "this method changes the receiver" or "this type contains a mutex".

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given x := 4 and p := &x, what does *p = 9 do?

    *p names the variable p points at, which is x, so assigning to it changes x.
  2. 2. What is the zero value of var p *string?

    Every pointer type has nil as its zero value. Declaring a nil pointer is fine; dereferencing it panics.
  3. 3. What happens when you run var p *int; fmt.Println(*p)?

    The program compiles, but at run time dereferencing a nil pointer panics with "invalid memory address or nil pointer dereference".
  4. 4. For a, b := 1, 1; pa, pb := &a, &b, what is pa == pb?

    Pointer equality compares addresses (identity), not the values stored there. Use *pa == *pb to compare the values.
  5. 5. Which line is NOT valid Go?

    Go has no pointer arithmetic. The other three compile (new with an expression needs Go 1.26 or later).

Summary

  • &x gives the address of x; *p reads or writes the variable p points to. The type of the pointer is *T.
  • The zero value of a pointer is nil. Dereferencing nil panics, so check when nil is possible.
  • Pointers to structs let you write p.Field without an explicit dereference.
  • Pointers are equal when they point at the same variable; there is no pointer arithmetic.
  • new(T) returns a pointer to a zeroed T; since Go 1.26 new(expr) allocates and initializes in one step.
  • Use pointers to modify, to share, to avoid copying large values, or to model "absent". Default to values otherwise.

Next: Pointers, Values and Functions