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 <n...@craig-wood.com> -- http://www.craig-wood.com/nick

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to