Get all attributes with zero value using reflection

74 views
Skip to first unread message

Rayland

unread,
Aug 3, 2016, 2:34:18 AM8/3/16
to golang-nuts
Hi all, 

How can I use reflect to detect all fields that have the zero value, on a pointer object?


Thank you

Axel Wagner

unread,
Aug 3, 2016, 4:35:26 AM8/3/16
to Rayland, golang-nuts
You use
and read the docs :)

Don't take this the wrong way, but reflect isn't for the gentle-spirited, it's ugly, errorprone and hard. You probably don't want to use it and if you need to use it, you should first really understand how (and have a good understanding of how go works). Otherwise you are going to write broken, unmaintainable and ugly programs. So there needs to be some of the heavy-lifting on your part, it can't all come from mailing lists :)

--
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...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Nick Craig-Wood

unread,
Aug 3, 2016, 7:19:37 AM8/3/16
to Rayland, golang-nuts
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
Reply all
Reply to author
Forward
0 new messages