I have a service, written in golang, that can be initialized with some options. Options are passed as a struct to a constructor function. The constructor function uses default values for option fields that weren't included. Here's an example:
type Service struct {
options Options
}
type Options struct {
BoolOption bool
StringOption string
}
const (
DefaultBoolOption = true
DefaultStringOption = "bar"
)
func New(opts Options) *Service {
if !opts.BoolOption {
opts.BoolOption = DefaultBoolOption
}
if len(opts.StringOption) < 1 {
opts.StringOption = DefaultStringOption
}
return &Service{options: opts,}
}
...
// elsewhere in my code
o := Options{BoolOption: false,}
// sets s.options.BoolOption to true!!!
s := New(o)
My problem is that for bool
or int
option types, I can't tell whether or not a field value was set in the Options struct. For example, was BoolOption
set to false or just not initialized?
One possible solution would be to use strings for all of my Options fields. For instance, BoolOption
would be "false"
rather than false
. I could then check the length of the string to check if it was initialized.
Are there better solutions?