How can I add a new boolean property to a Golang struct and set the default value to true?

huangapple go评论74阅读模式
英文:

How can I add a new boolean property to a Golang struct and set the default value to true?

问题

我有一个与实体对应的用户结构体。如何添加一个新的属性active并将默认值设置为true

我还可以通过一些简单的方法将所有现有实体的该属性值设置为true吗?

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

额外问题:我不太理解结构体中的语法。这三个冒号代表什么?JSON字符串周围的``是什么意思?

英文:

I have a user struct that corresponds to an entity. How can I add a new property active and set the default value to true?

Can I also set the value of that property to true for all existing entities by some easy method?

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

Bonus questions: I don't quite understand the syntax in the struct. What do the three columns represent? What do the JSON strings have ``around them?

答案1

得分: 2

//你不能改变声明的类型。
type User struct {
Id int64 json:"id"
Name string json:"name"
}
//相反,你可以构造一个新的类型,嵌入已存在的类型。
type ActiveUser struct {
User
Active bool
}
//你可以直接实例化类型。
user := User{1, "John"}
//你也可以为你的类型提供构造函数。
func MakeUserActive(u User) ActiveUser {
auser := ActiveUser{u, true}
return auser
}
activeuser := MakeUserActive(user)

你可以看到它的工作原理:https://play.golang.org/p/UU7RAn5RVK

英文:
//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)

You can see it works https://play.golang.org/p/UU7RAn5RVK

答案2

得分: 1

你必须在将结构类型传递给变量时将默认值设置为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字符串反序列化为对象字段,然后可以将其映射到结构中的特定字段。

英文:

You have to set the default value as true at the moment when you are passing the struct type to a variable, but this means you need to extend that struct with a new Active field.

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

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

json:"id" means that you are mapping the json decoded object field to the field id in your struct type. Practically you are deserialize the json string into object fields which later you can map to their specific field inside the struct.

huangapple
  • 本文由 发表于 2016年2月12日 17:25:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/35358946.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定