dongnao9525 2017-08-16 09:43
浏览 1550
已采纳

为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>
  • 写回答

1条回答 默认 最新

  • dsfs587465 2017-08-16 09:55
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?