刚开始的时候,一切都很顺利。
我有一个配置要在github.com/kelseyhightower/envconfig
包的帮助下从drivers
读取
type NXConfig struct {
Enable bool `default:"true"`
NxRate time.Duration `default:"300ms"`
NxDisconnectingChance int `default:"8"`
NxDisconnectionDuration time.Duration `default:"25s"`
}
var nxConfig NXConfig
envconfig.Process("NX", &nxConfig)
conf = &Config{
NxConfig: &nxConfig,
}
字符串
在开发/测试模式中,预设值可让结构成员准备好使用true
、300ms
、8
、25ms
进行测试。
但是我的配置现在也依赖于生成的Item
类型。
我不能输入这个类型来将默认值放在它的变量成员前面,因为它是一个生成的类型:它是共享的,没有意义。但是,我需要用默认值初始化它。
我先试过了:
type NXConfig struct {
Enable bool `default:"true"`
Item nx.ActivationData {IpAddress: "127.0.0.1", PortNumber: 3000, ItemId: "99", ItemType: "990"}
NxRate time.Duration `default:"300ms"`
NxDisconnectingChance int `default:"8"`
NxDisconnectionDuration time.Duration `default:"25s"`
}
型
但nx.ActivationData
与其具有nil
或0的成员保持一致。
我试过第二次:
type NXConfig struct {
Enable bool
Item nx.ActivationData
NxRate time.Duration
NxDisconnectingChance int
NxDisconnectionDuration time.Duration
}
型
删除struct
中的默认值,创建构造函数:
func NewNXConfig() *NXSimulatorConfig {
return &NXConfig{ Enable: true,
Item: nx.ActivationData {IpAddress: "127.0.0.1", PortNumber: 3000, ItemId: "99", ItemType: "990"},
NxRate: time.Duration(time.Millisecond) * time.Duration(300),
NxDisconnectingChance: 8,
NxDisconnectionDuration: time.Duration(time.Millisecond) * time.Duration(25)}
}
型
我把最后一行改成:
var nxConfig *NXConfig = NewNXConfig()
envconfig.Process("NX", nxConfig)
conf = &Config{
NxConfig: nxConfig,
}
型
成功了。但这是一条漫长的路...
如何声明一个struct
的子成员的默认值,从同它的外部,同default
?
我该怎么写Item nx.ActivationData {IpAddress: "127.0.0.1", PortNumber: 3000, ItemId: "99", ItemType: "990"}
个
声明,使其分配其成员?
1条答案
按热度按时间nkhmeac61#
实现配置的最简单方法是为
nx.ActivationItem
的配置添加一个结构体,然后从该配置构建nx.ActivationItem
。作为奖励,您的配置现在也显式地显示了它的预期值,而不是嵌入生成的结构体。字符串