I have a Favorites
struct with a slice field:
type Favorites struct {
Color string
Lunch string
Place string
Hobbies []string
}
and I have a Person
which contains the other struct:
type Person struct {
Name string
Favorites Favorites
}
I'd like to see if the Favorites
field is set on Person. For other types of fields, for example, a string or an int, I would compare that field to the zero value ("" or 0 respectively).
If I try to compare with the zero as below I get the error invalid operation: p2.Favorites == zeroValue (struct containing []string cannot be compared)
:
p2 := Person{Name: "Joe"}
zeroValue := Favorites{}
if p2.Favorites == zeroValue {
fmt.Println("Favorites not set")
}
This matches what is defined in the spec (https://golang.org/ref/spec#Comparison_operators).
Is there anyway to do this comparison other than tediously comparing every single field (and having to remember to update it if the struct changes)?
One option is to make the Favorites field a pointer to the struct instead of the struct itself and then just compare with nil, but this is in a large codebase so I'd rather not make potentially far-reaching changes in this case.