在golang中为struct字段分配默认值

Roh*_*nil 4 go

我想为struct field指定默认值__CODE__.我不确定是否可能,但在创建/初始化结构的对象时,如果我没有为该字段分配任何值,我希望它从默认值分配.知道如何实现它吗?

type abc struct {
    prop1 int
    prop2 int  // default value: 0
}
obj := abc{prop1: 5}
// here I want obj.prop2 to be 0
Run Code Online (Sandbox Code Playgroud)

Fli*_*mzy 15

这是不可能的.您可以做的最好的是使用构造函数方法:

type abc struct {
    prop1 int
    prop2 int  // default value: 0
}

func New(prop1 int) abc {
    return abc{
        prop1: prop1,
        prop2: someDefaultValue,
    }
}
Run Code Online (Sandbox Code Playgroud)

但是请注意,Go中的所有值都会自动默认为零值.a的零值int已经存在0.因此,如果您想要的默认值是字面上的0,那么您已经免费获得了该值.如果您想要某个类型的零值以外的某个默认值,则只需要构造函数.