At the beginning, everything is going well.
I have a configuration to read from drivers with the help of the package github.com/kelseyhightower/envconfig
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,
}
in dev/test mode, the default valuations allow the struct members to be ready for testing with true, 300ms, 8, 25ms.
But it comes that my config relies now on a generated Item type too.
I cannot enter this type to put default values in front of its variable members, because it's a generated type: it is shared, and it would have no sense.
But I need it, however, to be initialized with default values.
I've attempted first:
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"`
}
but nx.ActivationData stays with it's members having nil or 0.
I've attempted second:
type NXConfig struct {
Enable bool
Item nx.ActivationData
NxRate time.Duration
NxDisconnectingChance int
NxDisconnectionDuration time.Duration
}
removing the default values in the struct, and creating a constructor:
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)}
}
And I have changed the final lines with:
var nxConfig *NXConfig = NewNXConfig()
envconfig.Process("NX", nxConfig)
conf = &Config{
NxConfig: nxConfig,
}
It worked. But it was a long path...
How to declare a default value for a struct child member, from with its outside, with default?
How should have I written the
Item nx.ActivationData {IpAddress: "127.0.0.1", PortNumber: 3000, ItemId: "99", ItemType: "990"}
declaration in my parent struct, to make it assign its members?
The simplest way to achieve your config is to add a struct for the config of the
nx.ActivationItemand than build thenx.ActivationItemfrom said config. As a bonus your config is now also explicit in it's expected values, rather than embedding a generated struct.