Dereferencing pointer

The code below requires that I use personPtr.age = personPtr.age + 1. I was thinking I would have to dereference the pointer like so *personPtr.age = *personPtr.age + 1 but the compiler complains about this latter option. Why do I not need to dereference the pointer?

package main

import (
	"fmt"
)

type person struct {
	name string
	age int
}

func happyBirthday(personPtr *person)  {
	personPtr.age = personPtr.age + 1
}

func main() {
	youngMonkey := person{name: "YoungMonkey", age: 0}
	happyBirthday(&youngMonkey)
	fmt.Println(youngMonkey.age)
}

Go performs automatic dereferencing for struct data type in its specification. Hence, you do not need to de-reference it explicitly. Quote:

As with selectors, a reference to a non-interface method with a value receiver using a pointer will automatically dereference that pointer: pt.Mv is equivalent to (*pt).Mv .

(More info here: https://golang.org/ref/spec#Selectors, https://golang.org/ref/spec#Method_values)

You only need to de-reference slice, map, or array if you’re passing in as a pointer (rare occasion for such deployment but that is another question). Example:

func myProcess(a *map[string]string) {
     t := (*a)["whatever"]
     ...
}
2 Likes

Thanks a bunch. That is very helpful.

1 Like