I'm a super beginner with Go and trying to teach myself through playing, so I apologies if I'm not being fantastically coherent. I'm trying to use two files. On file 1, I want to create an instance of Person (aged 30, named Peter). In this file, I want to be able to call Change, and have his name changed to Alex.
This works if I just call user.NameChange - but not change(user). How do I go about getting this to work as intended?
Greatly appreciated.
FILE 1:
package main
import (
"fmt"
"greetings/person"
)
func Change(user person.User) {
user.NameChange()
}
func main() {
user := person.User{"Peter", 30}
fmt.Println(user) // returns "Peter"
Change(user)
fmt.Println(user) // returns "Peter" - Expected "Alex"
}
FILE 2:
package person
type User struct {
Name string
Age int
}
func (u *User) NameChange() {
u.Name = "Alex"
}
Function parameters are passed by value, therefore, when you enter Change function, you get a copy of User struct in your user variable. And you call NameChange on a copy, not the original. To change the original struct, you have to pass the struct as a pointer.
File1:
package main
import (
"fmt"
"greetings/person"
)
// pass User as a pointer instead of value
func Change(user *person.User) {
user.NameChange()
}
func main() {
user := person.User{"Peter", 30}
fmt.Println(user) // returns "Peter"
Change(&user)
fmt.Println(user) // returns "Peter" - Expected "Alex"
}
That's happening because the receiver is defined as a value (as opposed to a pointer). If you change Change
to
func Change(user *person.User) {
user.NameChange()
}
and call it using
Change(&user)
then you should be good.