56

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 ?

0

1 Answer 1

67

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Just as a comment to help others if needed - make sure that your signature definition is a pointer: func (u *User) Modify(), not simply as a value: func (u User) Modify() - This caught me out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.