Level: BeginnerGo Programs

Go Pointer Programs with Output: Swap, nil Checks and new()

Updated 16 min read
Go Pointer Programs featured image: swap, nil check and pointer output

Go pointer programs work with memory addresses, which let a function change a value that lives somewhere else. Pointers sound scary, but in Go they are safe and simple: there is no pointer arithmetic, and the garbage collector frees memory for you. In this post, you will write fourteen pointer programs with their exact output, and then practice the pointer questions that test your understanding of copies, nil and addresses.

You already met pointer receivers in our Go struct programs. For the theory, read Go pointers explained simply. Our Go function programs also showed that Go passes copies, which is why pointers matter. All programs were tested on Go 1.27.

What are Go Pointer Programs?

Go pointer programs use a pointer, which is a variable that stores the memory address of another variable. The & operator gives you the address of a value, and the * operator follows the address to read or change the value.

Think of a house and its postal address. The house is the value. The address on a card is the pointer. If you give a friend the card, they can visit the real house and paint the door, instead of painting a copy.

Why Go Pointer Programs Matter

Go copies every argument, so Go pointer programs exist for a good reason. Without pointers, a function could never change your variable. Pointers also avoid copying big structs and let you show “no value” with nil.

  • Changing data: update a struct or counter from another function.
  • Speed: pass an 8-byte address instead of copying a large struct.
  • Optional values: a *int can be nil, which means “not set”, while an int is always a number.
  • Interviews: nil pointer panics and swap programs are common questions.

How Go Pointer Programs Work

When you write p := &x, Go stores the address of x in p. Reading *p follows that address and gives you the value of x. Writing *p = 10 changes x itself, because both point to the same memory.

Go pointer programs diagram showing a variable, its address and a pointer that points to it
The pointer p stores the address of x, so *p reads and changes the same memory as x.

The table below sums up the pointer syntax.

SyntaxMeaningExample
&xAddress of xp := &x
*TType “pointer to T”var p *int
*pValue at the addressfmt.Println(*p)
*p = vChange the value*p = 42
new(T)Make a zero T, return its addressp := new(int)
nilPointer that points nowhereif p == nil { }

Basic Go Pointer Programs

These first Go pointer programs show the two operators in action.

Program 1: Address and Value

This program uses the same names as the diagram above: x is the value and p is the pointer.

package main

import "fmt"

func main() {
    x := 25   // x is a normal int variable
    p := &x   // &x is the address of x, so p points to x
    fmt.Println("x =", x)
    fmt.Println("*p =", *p) // *p follows the address and reads the value

    *p = 40 // change the value at that address, which is x
    fmt.Println("x after *p = 40:", x)
    fmt.Println(p == &x) // p holds exactly the address of x
}
x = 25
*p = 25
x after *p = 40: 40
true

First, p := &x stores the address of x in p. Then *p = 40 writes through that address, so x becomes 40. We do not print the address itself, because it changes on every run.

Program 2: Swap Two Numbers with Pointers

package main

import "fmt"

// swap gets the addresses of two ints and swaps the values stored there.
func swap(first, second *int) { // *int means "pointer to an int"
    *first, *second = *second, *first // a plain swap: both right side values are read first
}

func main() {
    apples, oranges := 7, 99
    swap(&apples, &oranges) // send the addresses, not copies
    fmt.Println(apples, oranges)
}
99 7

main sends the addresses of both variables with &. Inside swap, the * follows each address and swaps the real values. Without pointers, swap would only swap its own copies.

Program 3: Increment a Counter from a Function

package main

import "fmt"

// incrementCopy gets a copy, so the caller sees no change.
func incrementCopy(count int) { count++ }

// increment gets a pointer, so it changes the caller's variable.
func increment(count *int) { *count++ } // add one to the value at the address

func main() {
    visits := 0
    incrementCopy(visits)
    fmt.Println(visits) // still 0
    increment(&visits)
    increment(&visits)
    fmt.Println(visits) // now 2
}
0
2

*count++ means “add one to the value at count”. The copy version changes only its own count, so it has no effect on visits. The pointer version changes visits twice.

Program 4: new() for a Zero Value Pointer

package main

import "fmt"

func main() {
    number := new(int) // new(int) makes a zero int and returns its address
    fmt.Println(*number)
    *number = 15
    fmt.Println(*number)

    text := new(string) // a pointer to an empty string
    fmt.Printf("%q\n", *text) // %q prints the string with quotes
}
0
15
""

new(T) creates a zero value of type T and returns its address. So *number starts at 0 and *text starts as an empty string. It is the same as writing var value T and then taking &value.

Pointers to Structs in Go Pointer Programs

Most real Go pointer programs use pointers to structs.

Program 5: A Simple Pointer to a Struct

Start here if structs and pointers together feel new. One pointer, one change, one print.

package main

import "fmt"

// Book holds a title and a price.
type Book struct {
    Title string
    Price int
}

func main() {
    book := Book{Title: "Go Basics", Price: 300}
    bookPointer := &book // bookPointer points to book

    bookPointer.Price = 250 // Go follows the pointer for you
    fmt.Println(book.Price) // the original book changed
}
250

bookPointer holds the address of book. When you write bookPointer.Price = 250, Go goes to that address and changes the real book. That is why book.Price prints 250.

Program 6: Change a Struct through a Pointer

package main

import "fmt"

// Player is a game player with a score.
type Player struct {
    Name  string
    Score int
}

// addPoints adds points to the player that the pointer points to.
func addPoints(player *Player, points int) {
    player.Score += points // same as (*player).Score += points
}

func main() {
    asha := Player{"Asha", 10}
    addPoints(&asha, 25)
    fmt.Println(asha)
}
{Asha 35}

main passes &asha, so addPoints works on the real player. Go lets you write player.Score instead of (*player).Score. It follows the pointer for you.

Program 7: Return a Pointer from a Function

package main

import "fmt"

// Order is a shop order with a status.
type Order struct {
    ID     int
    Status string
}

// newOrder builds an order and returns its address.
func newOrder(id int) *Order {
    order := Order{ID: id, Status: "created"}
    return &order // safe in Go
}

func main() {
    order := newOrder(501)
    order.Status = "shipped" // change it through the pointer
    fmt.Println(*order)      // *order prints the value, not the address
}
{501 shipped}

In C, returning the address of a local variable is a bug. In Go, it is safe, because the compiler moves order to the heap when its address escapes the function. So the caller can keep using it.

Program 8: Pointers in a Slice of Structs

package main

import "fmt"

// Item is a product with a stock count.
type Item struct {
    Name  string
    Stock int
}

func main() {
    items := []*Item{{"pen", 5}, {"book", 0}, {"bag", 2}} // a slice of pointers to Item

    // Step 1: restock any item that has run out.
    for _, item := range items {
        if item.Stock == 0 {
            item.Stock = 10 // item points to the real Item
        }
    }

    // Step 2: print every item.
    for _, item := range items {
        fmt.Println(item.Name, item.Stock)
    }
}
pen 5
book 10
bag 2

item is a copy of each pointer, but every copy still points to the real item. So the restock change sticks, and the book now shows 10.

Nil and Optional Go Pointer Programs

These Go pointer programs show how nil helps you model missing data.

Program 9: A New Pointer Starts as nil

Before you use nil checks, see what an empty pointer looks like.

package main

import "fmt"

func main() {
    var pointer *int // declared but not given an address yet
    fmt.Println(pointer == nil, pointer) // nil means "points to nothing"

    score := 7
    pointer = &score // now it points to score
    fmt.Println(pointer == nil, *pointer)
}
true <nil>
false 7

A pointer you declare without a value is nil, the zero value for pointers. After pointer = &score, it holds a real address. Then *pointer safely reads 7.

Program 10: Check for nil Before Using a Pointer

package main

import "fmt"

// Profile holds a short bio.
type Profile struct{ Bio string }

// bioOf returns the bio, or a message when there is no profile.
func bioOf(profile *Profile) string {
    if profile == nil {
        return "(no profile)"
    }
    return profile.Bio
}

func main() {
    var missing *Profile // nil, points to nothing
    found := &Profile{Bio: "Go developer"}
    fmt.Println(bioOf(missing))
    fmt.Println(bioOf(found))
}
(no profile)
Go developer

A nil pointer points to nothing. Reading profile.Bio on a nil pointer would panic, so bioOf checks first. It returns a friendly message instead of crashing.

Program 11: Optional Value with *int

package main

import "fmt"

// Filter has an optional minimum age.
type Filter struct {
    MinAge *int // nil means "no filter"
}

// describe turns the filter into a short sentence.
func describe(filter Filter) string {
    if filter.MinAge == nil {
        return "all ages"
    }
    return fmt.Sprintf("age %d and above", *filter.MinAge)
}

func main() {
    zero := 0
    eighteen := 18
    fmt.Println(describe(Filter{}))                  // MinAge is nil
    fmt.Println(describe(Filter{MinAge: &zero}))     // MinAge points to 0
    fmt.Println(describe(Filter{MinAge: &eighteen})) // MinAge points to 18
}
all ages
age 0 and above
age 18 and above

A plain int cannot tell “not set” from 0. A *int can, because nil means “not set” and a pointer to 0 means “zero”. That is why APIs and JSON structs often use pointers for optional fields.

Program 12: Pointer to a Pointer

package main

import "fmt"

func main() {
    number := 5
    pointer := &number           // pointer holds the address of number
    pointerToPointer := &pointer // this holds the address of pointer
    **pointerToPointer = 50      // follow two addresses, then change number
    fmt.Println(number, *pointer, **pointerToPointer)
}
50 50 50

pointerToPointer holds the address of pointer, which holds the address of number. Two stars follow both addresses and reach number. You rarely need this in Go, but interviewers like to ask about it.

Program 13: Pointer to an Array

package main

import "fmt"

// doubleAll doubles every number in the array the pointer points to.
func doubleAll(numbers *[4]int) {
    for i := range numbers { // range works through the pointer
        numbers[i] *= 2
    }
}

func main() {
    numbers := [4]int{1, 2, 3, 4}
    doubleAll(&numbers)
    fmt.Println(numbers)
}
[2 4 6 8]

Arrays are copied when passed, so we send a pointer. The loop then changes the real array. With a slice, you would not need a pointer, because a slice already shares its array.

Program 14: Methods with a nil Receiver

package main

import "fmt"

// Node is one box in a linked list. Next points to the following box.
type Node struct {
    Value int
    Next  *Node // nil when this is the last node
}

// Len counts the nodes from this one to the end.
func (node *Node) Len() int {
    if node == nil {
        return 0 // an empty list has length 0
    }
    return 1 + node.Next.Len() // count this node, then the rest
}

func main() {
    third := &Node{Value: 3, Next: nil}
    second := &Node{Value: 2, Next: third}
    list := &Node{Value: 1, Next: second}
    var empty *Node // a nil list
    fmt.Println(list.Len(), empty.Len())
}
3 0

Len counts one for the current node, then asks the next node for its length. At the end, node.Next is nil, and Len returns 0 instead of panicking. A pointer method can run on a nil receiver, as long as it checks for nil.

Value vs Pointer in Go Pointer Programs

Most Go pointer programs come down to one choice. The diagram and table below compare passing a value with passing a pointer.

Go pointer programs comparison of passing a value and passing a pointer
Passing a value copies the data, while passing a pointer shares the original so changes are visible.
FeaturePass a valuePass a pointer
What is copiedThe whole valueAn 8-byte address
Function can change caller’s dataNoYes
Can be nilNoYes, check before use
Safe from accidental changesYesNo
Best forSmall, read-only dataBig structs or updates

In short, pass values by default for small types. Use pointers when the function must change the data, or when the data is large.

Common Mistakes in Go Pointer Programs

  • Dereferencing nil: var p *int; *p = 1 panics, so check p != nil first.
  • Pointers to everything: small values like ints and short structs are fine to copy.
  • Pointers to maps and slices: you rarely need *map or *[]T, because they already share data. The exception is when a function must reassign the slice itself.
  • Expecting pointer arithmetic: Go has none, so p++ on a pointer does not compile.
  • Printing addresses in tests: addresses change every run, so never compare them as text.

Best Practices for Go Pointer Programs

  • Use pointer receivers for methods that change a struct.
  • Return pointers from constructors like NewOrder, since callers usually change the value.
  • Check for nil at the start of functions that accept pointers.
  • **Use *T for optional fields** in JSON and database structs.
  • Keep pointers simple, and avoid pointer-to-pointer unless you truly need it.

Go Pointer Programs Interview Questions and Answers

Interviewers use short Go pointer programs to test how pointers behave. Each program is complete, with real output from Go 1.27.

Basic Questions on Go Pointer Programs

Q1. What happens when you dereference a nil pointer?

package main

import "fmt"

func main() {
    var pointer *int      // nil, points to nothing
    fmt.Println(*pointer) // reading through nil crashes
}
panic: runtime error: invalid memory address or nil pointer dereference

The program crashes with a panic. This is the most common runtime error in Go, so always check pointers that might be nil.

Q2. Does Go support pointer arithmetic?

No. You cannot add to or subtract from a pointer like in C. This removes a whole class of memory bugs. The unsafe package can do it, but normal code should never need it.

Q3. What is the difference between new and make?

new(T) returns a *T pointing to a zero value, and works for any type. make only creates slices, maps and channels, and returns the ready value itself, not a pointer.

package main

import "fmt"

func main() {
    slicePointer := new([]int)  // a pointer to a nil slice
    numbers := make([]int, 2)   // a ready slice with 2 zeros
    fmt.Println(*slicePointer == nil, len(numbers))

    ages := make(map[string]int) // a ready, empty map
    ages["a"] = 1
    fmt.Println(ages)
}
true 2
map[a:1]

new([]int) gives a pointer to an empty slice that is still nil. make gives you a slice or map you can use straight away.

Q4. What does this program print?

package main

import "fmt"

func main() {
    first, second := 1, 1
    firstPointer := &first
    secondPointer := &second
    fmt.Println(firstPointer == secondPointer, *firstPointer == *secondPointer)

    samePointer := &first
    fmt.Println(firstPointer == samePointer)
}
false true
true

Two pointers are equal only if they point to the same variable. first and second hold the same number but live at different addresses.

Function and Struct Questions

Q5. What does this program print?

package main

import "fmt"

// reset sets its own copy of the pointer to nil.
func reset(pointer *int) {
    pointer = nil // changes only the local copy
}

func main() {
    score := 5
    pointer := &score
    reset(pointer)
    fmt.Println(pointer != nil, *pointer)
}
true 5

The function gets a copy of the pointer. Setting that copy to nil does not change the caller’s pointer, which still points to score.

Q6. What does this program print?

package main

import "fmt"

// grow adds 4 to the slice that the pointer points to.
func grow(numbers *[]int) {
    *numbers = append(*numbers, 4) // store the new slice back at the address
}

func main() {
    numbers := []int{1, 2, 3}
    grow(&numbers)
    fmt.Println(numbers)
}
[1 2 3 4]

Here the function must change the slice header itself, because append may return a new one. That is the one common case where a pointer to a slice makes sense. Returning the new slice is usually cleaner.

Q7. What does this program print?

package main

import "fmt"

// Box holds one number.
type Box struct{ Value int }

func main() {
    original := Box{1}
    pointer := &original   // points to original
    duplicate := *pointer  // *pointer makes a copy of the value
    pointer.Value = 2      // changes original
    duplicate.Value = 3    // changes only the copy
    fmt.Println(original.Value, pointer.Value, duplicate.Value)
}
2 2 3

pointer points to original, so changing pointer.Value changes original. But duplicate := *pointer makes a copy, so duplicate changes alone.

Q8. Is it safe to return the address of a local variable?

Yes. Go’s escape analysis sees that the address leaves the function and puts the variable on the heap. The garbage collector frees it later when nothing points to it.

Output Questions

Q9. What does this program print?

package main

import "fmt"

func main() {
    var pointers []*int
    for i := range 3 { // i takes 0, 1, 2
        pointers = append(pointers, &i) // save the address of this pass's i
    }
    for _, pointer := range pointers {
        fmt.Print(*pointer, " ")
    }
    fmt.Println()
}
0 1 2

Since Go 1.22, each loop pass has its own i, so every pointer points to a different variable. In older Go, this printed “3 3 3” or “2 2 2”.

Q10. What does this program print?

package main

import "fmt"

func main() {
    total := 10
    pointer := &total
    *pointer += 5 // total is now 15
    *pointer *= 2 // total is now 30
    fmt.Println(total)
}
30

Both lines change total through the pointer. First it becomes 15, then 30.

Q11. Why do Go APIs use pointers for optional JSON fields?

A plain field always has a value, so you cannot tell “the client sent 0” from “the client sent nothing”. A pointer field is nil when the value is missing, which keeps the two cases apart.

Q12. What does this program print?

package main

import "fmt"

// Car has a speed.
type Car struct{ Speed int }

// Faster adds 10 to the speed and returns the same car pointer.
func (car *Car) Faster() *Car {
    car.Speed += 10
    return car
}

func main() {
    car := &Car{}
    car.Faster().Faster().Faster() // three calls in a chain
    fmt.Println(car.Speed)
}
30

Each method returns the same pointer, so we can chain calls. This style is common in builder patterns.

Practice Task

This task mixes maps with Go pointer programs. Write a function updateStock(stock map[string]*int, item string, change int) that adds change to an item’s stock, and creates the item if it does not exist. Print the stock after three updates. Hint: when the item is missing, create a new int with new(int) and store its address.

Official Resources

Quick Recap

  • Go pointer programs use & to take an address and * to read or change the value.
  • Go passes copies, so pointers let a function change the caller’s data.
  • new(T) returns a pointer to a zero value, while make builds slices, maps and channels.
  • A nil pointer dereference panics, so check for nil first.
  • Go has no pointer arithmetic, and returning a pointer to a local variable is safe.

What’s Next?

Next, we learn how different types can share behaviour. Read Go interface programs with output, with shapes, Stringer and type switches. To revise structs first, see our Go struct programs.