I have some code that uses reflection to check for missing values in some structs. Here's a simplified version of if:
package main
import (
"fmt"
"reflect"
)
type Foo struct {
bar string
}
func main() {
foo := Foo{}
v := reflect.ValueOf(foo)
fmt.Println("bar has a value:", v.FieldByName("bar").IsValid())
}
(Playground: http://ift.tt/2hYOJgp)
I expected this to print "false", but it actually prints "true".
The golang documentation for Value.IsValid() states that "It returns false if v is the zero Value". AFAIK, the zero value for a string is an empty string.
I made it work by adding an additional check:
if f.Kind() == reflect.String && f.String() == "" {
But it feels kind of dirty and wrong. Any insight into why IsValid behaves the way it does?
Aucun commentaire:
Enregistrer un commentaire