Understanding calling function with pointer to struct

I remember understanding this issue (or something similar) in C or C++ several years ago.
If possible, I’d like some practical explanation using memory addresses, for example.

I’m referring to
https://play.golang.org/p/J_4aG29-jDa

If u is at memory location 1000, v at 2000 and y at 3000, what happens inside the Modify{1,2,3} functions?

The function Modify1 does not modify the passed User. The parameter u is local to the function. So assigning a new User pointer to it only has effect locally.

func Modify1(u *User) {
	u = &User{Name: "Paul"}
	fmt.Println("\t", u.Name)
}

The same is true for Modify2. Since the User is passed by value, locally modifying it has no effect outside the function.

func Modify2(u User) {
	u.Name = "Duncan"
}

If you want to modify a passed User so that it has effect outside the function, dereference the passed pointer and modify the referenced User.

package main

import "fmt"

type User struct {
	Name string
}

func main() {
	z := &User{Name: "Leto"}
	fmt.Println(z.Name)
	Modify4(z)
	fmt.Println(z.Name)
}

func Modify4(u *User) {
	u.Name = "Bob"
}

Output:

Leto
Bob

https://play.golang.org/p/dEzmV6xmw9P

Also take a look at the Go tour: https://tour.golang.org/methods/5

1 Like

I have no problems understanding Modify2.

As for Modify1, u is local fine. It’s scope is local but is it pointing to *User or to a copy of it?

You assign a new &User pointer to u. This does not change the User that was originally referenced by u.

Ok, I’ve understood.
I was overwriting u.

Thank you @lutzhorn

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