如何初始化结构体字段

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

How to initialize struct fields

问题

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

  1. type MyType struct {
  2. Field string
  3. }
  4. func main() {
  5. myVar := MyType{
  6. Field: "default",
  7. }
  8. }

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

英文:

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

  1. type MyType struct {
  2. Field string = "default"
  3. }

答案1

得分: 10

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

  1. type MyType struct {
  2. Field string
  3. }
  4. func New(fld string) *MyType {
  5. return &MyType{Field: fld}
  6. }
  7. func Default() *MyType {
  8. return &MyType{Field: "default"}
  9. }

此外,我强烈建议你阅读《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".

  1. type MyType struct {
  2. Field string
  3. }
  4. func New(fld string) *MyType {
  5. return &MyType{Field: fld}
  6. }
  7. func Default() *MyType {
  8. return &MyType{Field: "default"}
  9. }

Also I highly recommend going through Effective Go.

答案2

得分: 2

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

  1. func NewMyType() *MyType {
  2. myType := &MyType{}
  3. myType.Field = "default"
  4. return myType
  5. // 如果不需要特殊逻辑
  6. // return &MyType{"default"}
  7. }

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

英文:

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

  1. func NewMyType() *MyType {
  2. myType := &MyType{}
  3. myType.Field = "default"
  4. return myType
  5. // If no special logic is needed
  6. // return &myType{"default"}
  7. }

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:

确定