在golang中为struct字段分配默认值 [英] Assign default value for struct field in golang
问题描述
我想为 golang
中的struct字段指定默认值。我不确定是否有可能,但是在创建/初始化结构对象的时候,如果我没有给该字段赋值,我希望它被赋值为默认值。任何想法如何实现它?
类型abc结构{
prop1 int
prop2 int //默认值:0
}
obj:= abc {prop1:5}
//这里我想让obj.prop2为0
这是不可能的。你可以做的最好的方法是使用一个构造函数方法:
pre code> type abc struct {
prop1 int
prop2 int //默认值:0
}
func新建(prop1 int)abc {
返回abc {
prop1:prop1,
prop2:someDefaultValue ,
}
}
但是请注意,Go 自动默认为其零值。 int
的零值已经是 0
。所以如果你想要的默认值是字面上 0
,你已经免费获得了。如果您希望某个类型的零值以外的某个默认值,则只需要构造函数。
I want to assign default value for struct field in golang
. I am not sure if it is possible but while creating/initializing object of the struct, if I don't assign any value to the field, I want it to be assigned from default value. Any idea how to achieve it?
type abc struct {
prop1 int
prop2 int // default value: 0
}
obj := abc{prop1: 5}
// here I want obj.prop2 to be 0
This is not possible. The best you can do is use a constructor method:
type abc struct {
prop1 int
prop2 int // default value: 0
}
func New(prop1 int) abc {
return abc{
prop1: prop1,
prop2: someDefaultValue,
}
}
But also note that all values in Go automatically default to their zero value. The zero value for an int
is already 0
. So if the default value you want is literally 0
, you already get that for free. You only need a constructor if you want some default value other than the zero value for a type.
这篇关于在golang中为struct字段分配默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!