I have been looking and been struggling with this for a bit. I found this other SO question which put me in the right direction but isn't working: Quick way to detect empty values via reflection in Go.
My current code looks like this:
structIterator := reflect.ValueOf(user)
for i := 0; i < structIterator.NumField(); i++ {
field := structIterator.Type().Field(i).Name
val := structIterator.Field(i).Interface()
// Check if the field is zero-valued, meaning it won't be updated
if reflect.DeepEqual(val, reflect.Zero(structIterator.Field(i).Type()).Interface()) {
fmt.Printf("%v is non-zero, adding to update\n", field)
values = append(values, val)
}
}
However I have a fmt.printf which prints out the val and the reflect.Zero I have and even when they both are the same, it still goes into the if statement and every single field is read as non-zero even though that is clearly not the case. What am I doing wrong? I don't need to update the fields just add them to the slice values if they aren't zero.
Aucun commentaire:
Enregistrer un commentaire