Reputation: 3606
I have example play.golang.org/p/Y1KX-t5Sj9 where I define method Modify() on struct User
type User struct {
Name string
Age int
}
func (u *User) Modify() {
*u = User{Name: "Paul"}
}
in the main() I am defining struct literal &User{Name: "Leto", Age: 11} then call u.Modify(). That results in printing 'Paul 0' I like that struct field Name is changed , but what is the correct way to keep Age field ?
Upvotes: 57
Views: 69822
Reputation: 46562
Just modify the field you want to change:
func (u *User) Modify() {
u.Name = "Paul"
}
This is covered well in the Go tour which you should definitely read through, it doesn't take long.
Upvotes: 66