« Back to Index

Go: updating a pointer field value

View original Gist on GitHub

Tags: #go

updating a pointer field value.md

I have a struct with a field that’s a pointer, and I want to update the value.

The following code does that (notice the memory address for the field changes, which is what I would expect once I change the value)…

package main

import "fmt"

type S struct {
	F *int
}

func main() {
	s := new(S)
	fmt.Printf("%+v\n", s) // &{F:<nil>}

	i := 1
	s.F = &i
	fmt.Printf("%+v\n", s)    // &{F:0xc000018050}
	fmt.Printf("%+v\n", *s.F) // 1

	i2 := 2
	s.F = &i2
	fmt.Printf("%+v\n", s)    // &{F:0xc000018060}
	fmt.Printf("%+v\n", *s.F) // 2
}

Now, in the following example I’ve modified the code from s.F = &i2 to *s.F = i2 and I can see that the change is applied because when I print a dereference of the struct field I see the updated value 2 but the memory address appears to be the same as when the value was set to 1. This is because I didn’t assign a new memory address (like I did with &i2) but went directly to the memory location (e.g. *s.F) and updated the value.

package main

import "fmt"

type S struct {
	F *int
}

func main() {
	s := new(S)
	fmt.Printf("%+v\n", s) // &{F:<nil>}

	i := 1
	s.F = &i
	fmt.Printf("%+v\n", s)    // &{F:0xc000018050}
	fmt.Printf("%+v\n", *s.F) // 1

	i2 := 2
	*s.F = i2
	fmt.Printf("%+v\n", s)    // &{F:0xc000018050}
    fmt.Printf("%+v\n", *s.F) // 2
}

So the latter could be considered better because it doesn’t cause another allocation of memory.