DEV Community

Ben McNicholl
Ben McNicholl

Posted on

A [Very] Simple Approach to Pointers in Go

This is in no way an all encompassing view on pointers, and there are one or two areas where the explanation in this post doesn't quite cut the mustard, but I found it much easier to view pointers in this way, so thought I'd share.

Pointers can be tricky to understand. They are used mostly when we want to overwrite some data, rather than using Go's inbuilt actions of making a copy of some data once we decide to modify it (by default, Go passes by value).

Anything which is a value type will utilise Go's inbuilt copying functionality, in order to preserve the data. Anything which is a reference type object will be modifiable and will overwrite original data.

& refers to the address of a value
* refers to the value at that address

For example;

package main

import "fmt"

type house struct {
    occupant string
}

func (houseLocation *house) changeTenant(newTenant string) {
    (*houseLocation).occupant = newTenant
}

func main() {
    bensHouse := house{occupant: "Ben"}
    fmt.Printf("The tenant is: %v \n", bensHouse)
    houseAddress := &bensHouse
    fmt.Println("Changing tenant.....")
    houseAddress.changeTenant("Paul")
    fmt.Printf("The tenant is: %v \n", bensHouse)
}

Let's start with the main block.

bensHouse is of type house and has one occupant, me (Ben).

Now, my landlord owns 100 houses (he lives on a tropical island, drinking cold beers all day). The rental agency cannot ring him and say "there is an issue with Ben's house", he doesn't know which one that is! Instead, they have to get the address of my house, they do that using &bensHouse.

So, the value at houseAddress might now be:

35 Winecask Road
Richmond
Melbourne
3012
Australia

The rental agency needs to change the tenant, as I'm moving out. They do that by running the changeTenant function on the address of the house.

They pass my address (houseAddress) in to the changeTenant function, which expects to be passed an address (houseLocation) of the type address of a house (*house); when we pass a function something of type *, that function expects a description of that type, which in this instance is the address of the house.

(*houseLocation).occupant = newTenant

We want to change the values of the house, so we access the value at the address we passed to the function (bensHouse{occupant: "Ben"}) and change the tenant to be the newTenant, in this case, Paul.

> go run main.go
The tenant is: {Ben} 
Changing tenant.....
The tenant is: {Paul} 

Top comments (0)