2016-02-12 128 views
-1

我有一个用户结构对应于一个实体。我如何添加一个新的属性active并将默认值设置为true如何将新的布尔属性添加到Golang结构中并将默认值设置为true?

可我也通过一些简单的方法设置该属性true所有现有实体的价值?

type User struct { 
    Id    int64  `json:"id"` 
    Name   string `json:"name"` 
} 

奖金问题:我不太了解结构中的语法。这三列代表什么? JSON字符串在它们周围有什么?

+2

关于'JSON: “名字”'件事:http://stackoverflow.com/questions/10858787/what-are-the-uses-for-tags -in-去 – TheHippo

回答

0

你必须设置在你逝去的结构类型变量的时刻,因为真正的默认值,但这意味着你需要扩展该结构以新Active场。

type User struct { 
    Id    int64  `json:"id"` 
    Name   string `json:"name"` 
    Active   bool 
} 

user := User{1, "John", true} 

json:"id"意味着你在你的结构类型映射的JSON解码对象场场id。实际上,您将json字符串反序列化为对象字段,稍后您可以将其映射到结构中的特定字段。

1
//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

+0

我认为更地道是'NewUser',用'Active'设置为true时,这是默认值,并提供一个'停用()'方法。 –

相关问题