On 03/08/16 07:34, Rayland wrote:
> How can I use reflect to detect all fields that have the zero value, on
> a pointer object?
Here is a bit of code I wrote which overrides all the non zero fields in
one struct, from another which might be helpful for you to look at.
// SetDefaults for config from a to b
func (a *Config) SetDefaultsFrom(b *Config) {
if b == nil {
return
}
pt := reflect.TypeOf(a)
t := pt.Elem()
va := reflect.ValueOf(a).Elem()
vb := reflect.ValueOf(b).Elem()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
zero := reflect.Zero(field.Type)
aField := va.Field(i)
bField := vb.Field(i)
// Override the setting of b if it is at the default
if aField.Interface() == zero.Interface() {
aField.Set(bField)
}
}
}
I won't attempt to modify it to do exactly what you asked as that would
require reading the reflect docs again ;-)
--
Nick Craig-Wood <
ni...@craig-wood.com> --
http://www.craig-wood.com/nick