lib
(Luis Mendes)
January 31, 2019, 10:43am
1
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?
lutzhorn
(Lutz Horn)
January 31, 2019, 11:09am
2
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
lib
(Luis Mendes)
January 31, 2019, 11:59am
3
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?
lutzhorn
(Lutz Horn)
January 31, 2019, 12:09pm
4
You assign a new &User
pointer to u
. This does not change the User
that was originally referenced by u
.
lib
(Luis Mendes)
January 31, 2019, 4:29pm
5
Ok, I’ve understood.
I was overwriting u
.
Thank you @lutzhorn
system
(system)
Closed
May 1, 2019, 4:29pm
6
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.