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)
}
1 Like

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: The Go Programming Language Specification - The Go Programming Language, The Go Programming Language Specification - The Go Programming Language)

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"]
     ...
}
4 Likes

Thanks a bunch. That is very helpful.

1 Like

Hi,
btw, if you do

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

it works.

Yes, but don’t write it in that complicated way. In Go, we value readability and simplicity. Simply write:

func happyBirthday(p *person) {
	p.age++
}
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.