-1

How to iterate over the fields in a structure and check if they are not empty without explicit?

I have an example structure

type Example struct {
    Foo, Bar string
}

I can ofc check explicitly if every field is not "", but I dont want to do that this way. Is there any simple way to accomplish what I need?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
dannyx
  • 33
  • 1
  • 5
  • 2
    With `reflect` package you can loop over struct fields and check their values. – mkopriva Aug 02 '21 at 11:52
  • 1
    See possible duplicate [How to check for an empty struct?](https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct) – icza Aug 02 '21 at 12:22
  • It's entirely different question. Im asking about fields in structure, not how to check for an empty struct. – dannyx Aug 03 '21 at 16:14
  • Does this answer your question? [How to check for an empty struct?](https://stackoverflow.com/questions/28447297/how-to-check-for-an-empty-struct) – Grokify Aug 05 '21 at 08:13

2 Answers2

5

If want to check if all fields have the zero value you could simply check

var foo Example
if foo == (Example{}) {
  // ...
}

go initializes all struct fields with the zero value (in case of a string the empty string ""). Keep in mind that this probably not works as expected if the struct has fields with not comparable types (i.e. of type pointer, slice or map).

You can use the methods of reflect.Value to iterate the fields and compare the values (like reflect.DeepEqual() does). But in most cases it is best to simply write a function which explicitly does the check.

gregor
  • 4,733
  • 3
  • 28
  • 43
4

I suggest you to use reflect package, as suggested mkopriva. Write it once and use it for all struct that you need. For example, i adapted a scratch found here

func IsEmpty(object interface{}) (bool, error) {
//First check normal definitions of empty
if object == nil {
    return true, nil
} else if object == "" {
    return true, nil
} else if object == false {
    return true, nil
}
//Then see if it's a struct
if reflect.ValueOf(object).Kind() == reflect.Struct {
    // and create an empty copy of the struct object to compare against
    empty := reflect.New(reflect.TypeOf(object)).Elem().Interface()
    if reflect.DeepEqual(object, empty) {
        return true, nil
    } else {
        return false, nil
    }
}
return false, errors.New("Check not implementend for this struct")  }