2 回答

TA贡献2011条经验 获得超2个赞
//You can't change declared type.
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//Instead you construct a new one embedding existent
type ActiveUser struct {
User
Active bool
}
//you instantiate type literally
user := User{1, "John"}
//and you can provide constructor for your type
func MakeUserActive(u User) ActiveUser {
auser := ActiveUser{u, true}
return auser
}
activeuser := MakeUserActive(user)
你可以看到它的工作原理https://play.golang.org/p/UU7RAn5RVK

TA贡献2051条经验 获得超10个赞
在将结构类型传递给变量时,您必须将默认值设置为 true,但这意味着您需要使用新Active字段扩展该结构。
type User struct {
Id int64 `json:"id"`
Name string `json:"name"`
Active bool
}
user := User{1, "John", true}
json:"id"意味着您将 json 解码的对象字段映射到id结构类型中的字段。实际上,您将 json 字符串反序列化为对象字段,稍后您可以将其映射到结构中的特定字段。
- 2 回答
- 0 关注
- 323 浏览
添加回答
举报