以下问题有多种答案/技巧:
如何将默认值设置为golang结构? 如何初始化结构在golang
我有几个答案,但还需要进一步讨论。
以下问题有多种答案/技巧:
如何将默认值设置为golang结构? 如何初始化结构在golang
我有几个答案,但还需要进一步讨论。
当前回答
一种可能的想法是编写单独的构造函数
//Something is the structure we work with
type Something struct {
Text string
DefaultText string
}
// NewSomething create new instance of Something
func NewSomething(text string) Something {
something := Something{}
something.Text = text
something.DefaultText = "default text"
return something
}
其他回答
Force a method to get the struct (the constructor way). From this post: A good design is to make your type unexported, but provide an exported constructor function like NewMyType() in which you can properly initialize your struct / type. Also return an interface type and not a concrete type, and the interface should contain everything others want to do with your value. And your concrete type must implement that interface of course. This can be done by simply making the type itself unexported. You can export the function NewSomething and even the fields Text and DefaultText, but just don't export the struct type something. Another way to customize it for you own module is by using a Config struct to set default values (Option 5 in the link). Not a good way though.
一种可能的想法是编写单独的构造函数
//Something is the structure we work with
type Something struct {
Text string
DefaultText string
}
// NewSomething create new instance of Something
func NewSomething(text string) Something {
something := Something{}
something.Text = text
something.DefaultText = "default text"
return something
}
对于Go结构体中的默认值,我们使用匿名结构:
Person := struct {
name string
age int
city string
}{
name: "Peter",
age: 21,
city: "Noida",
}
fmt.Println(人)
其中一种方法是:
// declare a type
type A struct {
Filed1 string
Field2 map[string]interface{}
}
因此,每当你需要一个自定义类型的新变量时,只需调用NewA函数,你也可以将函数参数化,可选地将值分配给struct字段
func NewA() *A {
return &A{
Filed1: "",
Field2: make(map[string]interface{}),
}
}
结构体
使这个程序更好的一个简单方法是使用结构体。struct是一种包含命名字段的类型。例如,我们可以这样表示一个圆:
type Circle struct {
x float64
y float64
r float64
}
type关键字引入了一个新类型。后面跟着类型的名称(Circle)、关键字struct(表示我们正在定义结构类型)和花括号内的字段列表。每个字段都有一个名称和类型。像函数一样,我们可以折叠具有相同类型的字段:
type Circle struct {
x, y, r float64
}
初始化
我们可以用多种方式创建Circle类型的实例:
var c圆 与其他数据类型一样,这将创建一个默认设置为0的本地Circle变量。对于结构体,0表示每个字段都被设置为相应的0值(0表示整型,0.0表示浮点数,""表示字符串,nil表示指针,…)
c := new(Circle)
这将为所有字段分配内存,将每个字段设置为0值并返回一个指针。(*圆圈)更多时候,我们想给每个字段一个值。我们可以用两种方法做到这一点。是这样的:
c := Circle{x: 0, y: 0, r: 5}
或者,如果我们知道字段的定义顺序,我们可以省略字段名:
c := Circle{0, 0, 5}