[英]how to modify struct fields in golang
I have example play.golang.org/p/Y1KX-t5Sj9 where I define method Modify() on struct User我有示例play.golang.org/p/Y1KX-t5Sj9 ,我在其中定义了 struct User 上的方法 Modify()
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() .在 main() 我定义结构文字&User{Name: "Leto", Age: 11}然后调用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 ?这导致打印 ' Paul 0 ' 我喜欢结构字段 Name已更改,但保留Age 字段的正确方法是什么?
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.这在Go 导览中有很好的介绍,您绝对应该通读一遍,不会花很长时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.