how to modify struct fields in golang

Viewed 45009

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 ?

1 Answers

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.

Related