Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign default value for struct field [duplicate]

Tags:

go

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
like image 749
Rohanil Avatar asked Aug 16 '17 09:08

Rohanil


People also ask

Can you set default values in a struct?

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.

Can struct have default values C++?

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.

Do structs need destructor?

"A struct cannot have a destructor. A destructor is just an override of object.


1 Answers

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.

like image 91
Flimzy Avatar answered Oct 05 '22 23:10

Flimzy