如何初始化结构体字段

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

How to initialize struct fields

问题

你可以在golang类型中如下初始化字段:

type MyType struct {
    Field string
}

func main() {
    myVar := MyType{
        Field: "default",
    }
}

在上面的示例中,我们定义了一个名为MyType的结构体类型,并在其中声明了一个名为Field的字符串字段。在main函数中,我们创建了一个myVar变量,并将Field字段初始化为"default"。

英文:

How can to initialize any fields in golang types? For example:

type MyType struct {
    Field string = "default" 
} 

答案1

得分: 10

你不能像那样设置“默认”值,你可以创建一个默认的“构造函数”函数来返回默认值,或者简单地假设空/零值是“默认值”。

type MyType struct {
    Field string
} 

func New(fld string) *MyType {
    return &MyType{Field: fld}
}

func Default() *MyType {
    return &MyType{Field: "default"}
}

此外,我强烈建议你阅读《Effective Go》(https://golang.org/doc/effective_go.html)。

英文:

You can't have "default" values like that, you can either create a default "constructor" function that will return the defaults or simply assume that an empty / zero value is the "default".

type MyType struct {
    Field string
} 

func New(fld string) *MyType {
	return &MyType{Field: fld}
}

func Default() *MyType {
	return &MyType{Field: "default"}
}

Also I highly recommend going through Effective Go.

答案2

得分: 2

没有直接的方法来做到这一点。常见的模式是提供一个New方法来初始化你的字段:

func NewMyType() *MyType {
    myType := &MyType{}
    myType.Field = "default"
    return myType

    // 如果不需要特殊逻辑
    // return &MyType{"default"}
}

另外,你也可以返回一个非指针类型。最后,如果你能够解决,你应该将结构体的零值设置为合理的默认值,这样就不需要特殊的构造函数了。

英文:

There is no way to do that directly. The common pattern is to provide a New method that initializes your fields:

func NewMyType() *MyType {
    myType := &MyType{}
    myType.Field = "default"
    return myType

    // If no special logic is needed
    // return &myType{"default"}
}

Alternatively, you can return a non-pointer type. Finally, if you can work it out you should make the zero values of your struct sensible defaults so that no special constructor is needed.

huangapple
  • 本文由 发表于 2015年5月25日 05:32:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/30428571.html
匿名

发表评论

匿名网友

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

确定