I want to assign default value for struct field in Go. 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
Default values can be assigned to a struct by using a constructor function. Rather than creating a structure directly, we can use a constructor to assign custom default values to all or some of its members. Another way of assigning default values to structs is by using tags.
When we define a struct (or class) type, we can provide a default initialization value for each member as part of the type definition. This process is called non-static member initialization, and the initialization value is called a default member initializer.
"A struct cannot have a destructor. A destructor is just an override of object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With