为结构字段指定默认值 [英] Assign default value for struct field

查看:52
本文介绍了为结构字段指定默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为Go中的struct字段分配默认值.我不确定是否可以,但是在创建/初始化该结构的对象时,如果不给该字段分配任何值,则希望从默认值中分配它.知道如何实现吗?

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

推荐答案

这是不可能的.最好的办法是使用构造函数方法:

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,
    }
}

但也请注意,Go 中的所有值自动默认为零值. int 的零值已经是 0 .因此,如果您想要的默认值实际上是 0 ,那么您已经免费获得了.如果您想要某种类型的默认值而不是零值,则只需要一个构造函数即可.

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.

这篇关于为结构字段指定默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆