为golang中的struct字段分配默认值[重复]

This question already has an answer here:

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
</div>

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.