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 關注
- 310 瀏覽
添加回答
舉報