I have a Go program here I'm using to test out a pointer error I'm having in a much larger http service program.
I have a pointer of a struct I'm wanting to pass to a function to initialize it. Naturally because it's a pointer, I shouldn't have to return anything. It should modify it directly.
However, that's not what is happening here.
func main () {
var thing *Thing
ModifyThing(thing)
fmt.Println(thing)
}
func ModifyThing (thing *Thing) {
thing = NewThing()
}
func NewThing () *Thing {
thing := Thing{}
return &thing
}
/// Output: <nil>
If I use NewThing()
on my thing
directly, I'll get an initialized pointer. However this doesn't work when I pass the pointer to a function that calls the same method. Is the memory location of my thing
not being passed how I'm expecting?
Your ModifyThing
doesn't actually modify thing
. It overwrites its local variable thing
with a new pointer to a new instance of Thing
, so it has no impact on anything else. If it actually modified thing
- say, thing.field = newValue
, that would be reflected in the caller.
If you wanted to overwrite the whole value pointed to by the pointer, you could also do that, but you have to explicitly overwrite the memory being pointed to rather than the pointer itself:
*thing = Thing{}
Notice we dereference *thing
, and overwrite its value with a new Thing
(not a new *Thing
!)
Everything in Go is passed by value, including pointers. Pointers point to a memory address, which can be a shared value. But the pointer itself is still copied on function call.