7

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
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Rohanil
  • 1,717
  • 5
  • 22
  • 47

1 Answers1

22

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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189