2. References

It's possible to define an empty pointer. For example, an empty pointer to an integer:

var p *int

fmt.Printf("value of p: %v\n", p)
// value of p: <nil>

Its zero value is nil, which means it doesn't point to any memory address. Empty pointers are also called "nil pointers".

Instead of starting with a nil pointer, it's common to use the & operator to get a pointer to its operand:

myString := "hello"      // myString is just a string
myStringPtr := &myString // myStringPtr is a pointer to myString's address

fmt.Printf("value of myStringPtr: %v\n", myStringPtr)
// value of myStringPtr: 0x140c050

A pointer is a variable that stores the memory address of another variable, rather than storing a value directly.

Think of it like this:

  • A normal variable is like a box that contains a value

  • A pointer is like a box that contains the address of another box

Creating a Pointer

Method 1: Nil Pointer (Empty)

  • *int means "pointer to an integer"

  • p doesn't point to anything yet

  • Its value is nil (nothing)

Method 2: Get Address with &

  • myString is a regular variable containing "hello"

  • &myString gets the address of myString

  • myStringPtr now stores that address

The & Operator: "Address Of"

& means "give me the address of this variable"

The * Operator: Two Uses

The * symbol does two different things depending on context:

Use 1: Declare a Pointer Type

Use 2: Dereference (Get the Value)

Dereference

The * operator dereferences a pointer to get the original value.

Unlike C, Go has no pointer arithmetic (which is covered in our Learn Memory Management coursearrow-up-right if you haven't taken it already).

Dereferencing means "follow the pointer to get the actual value"

Complete Example

Visual Representation

Why Use Pointers?

Reason 1: Modify Variables in Functions

Without pointers:

With pointers:

Reason 2: Efficiency with Large Data

Copying a pointer is cheaper than copying a large struct:

Key Syntax Summary

Symbol
Meaning
Example

*int

Type: pointer to int

var p *int

&x

Get address of x

ptr := &x

*ptr

Dereference: get value

value := *ptr

*ptr = 5

Set value through pointer

*ptr = 5

Common Pattern

1

Create a variable

2

Get its address

3

Read through pointer

4

Write through pointer

5

Original variable changed

What "No Pointer Arithmetic" Means

In C, you can do:

Go doesn't allow this. You can't do math on pointers. If you want to work with multiple elements, use slices instead.

Practice Understanding

Assignment

Complete the removeProfanity function.

It should use the strings.ReplaceAllarrow-up-right function to replace all instances of the following words in the input message with asterisks.

Word
Replacement

fubb

****

shiz

****

witch

*****

Solution

Dynamic Solution

Dynamic Replacement (Count the Letters)

If you want to automatically create the right number of asterisks:

How strings.Repeat Works