DEV Community

loading...
Cover image for Go Crash Course XI: Pointers

Go Crash Course XI: Pointers

Mofizur Rahman
Go Developer, Does Container-y stuff, Collects Stickers (in no particular order)
・2 min read

Pointers

If you are coming from something like c or c++ you should be familiar with pointers. Go has pointers too. A pointer is a memory address of a variable.

i := 10
fmt.Println(&i)
n := &i
fmt.Println(n)
fmt.Println(i)
*n = 15
fmt.Println(i)
Enter fullscreen mode Exit fullscreen mode

There are a few things going on in these few short lines of code.

Address of a variable

We can access the address of a variable with & operator. Here we have a variable i so &i gives us the memory address of i.

Pointer type

We create a new variable n with the value &i. If we check the type of n with fmt.Printf("%T\n", n) we will see the type is *int.

Pointer De-referencing

If we have a value of pointer type how do we get the actual value the pointer is pointing to? Thats where pointer de-referencing comes into play. We already seen an example of that actually.

*n = 15
Enter fullscreen mode Exit fullscreen mode

We de-reference n with the * operator to access the underlying value and assign 15 to it.

Passing pointers to function

If we want to persist the change to a variable passed to a function we need to pass it as pointers.

func pointer(x *int) {
    *x = 10
}

func value(x int) {
    x = 10
}

func main(){
    a := 5
    fmt.Println(a) // value is 5
    pointer(&a)
    fmt.Println(a) // value is 10
    a = 5
    fmt.Println(a) // value is 5
    value(a)
    fmt.Println(a) // value is still 5
}
Enter fullscreen mode Exit fullscreen mode

The same goes for arrays and slices as well. If we pass an array as value and make any changes to it, it wont persist.

func arrval(a []int) {
    a = append(a, 5)
}

func arrpointer(a *[]int) {
    *a = append(*a, 5)
}

func main() {
    ar := []int{1, 2, 3, 4}
    fmt.Println(ar) // [1 2 3 4]
    arrval(ar)
    fmt.Println(ar) // [1 2 3 4]
    arrpointer(&ar)
    fmt.Println(ar) // [1 2 3 4 5]
}
Enter fullscreen mode Exit fullscreen mode

One of the main exceptions to this is map. If we pass a map to a function. Map types are pointers by default. We will discuss this further when we talk about maps.

Pointer receivers

On methods we can have pointer receivers. If a type has a pointer receiver method any changes to the type in the method will persist. This was covered in the section about methods and partly in interfaces.

Next Steps

This is Part 11 of this Go crash course series.

Discussion (0)