jeudi 26 juillet 2018

Reflect zero not equal zero

I need to detect is value of some struct field is empty.
In this question I found the solution, but when I try it on playground operator == and func reflect.DeepEqual always returns false.
What am I doing wrong and how can I fix it?

Simple example:

func main() {
    s := ""
    v := reflect.ValueOf(s)
    t := reflect.TypeOf(s)

    zero := reflect.Zero(t)

    fmt.Println(zero == reflect.Zero(t)) // false
    fmt.Println(v == zero) // false 
    fmt.Println(v == reflect.Zero(t)) // false
}

My case:

type S struct {
    Empty string
    NotEmpty string
}

func main() {
    s := S{
        Empty: "",
        NotEmpty: "Some text",
    }


    v := reflect.ValueOf(s)
    for i := 0; i < v.NumField(); i++ {
        field := v.Field(i)

        fmt.Println(field, field == reflect.Zero(field.Type()))
    }
}





Aucun commentaire:

Enregistrer un commentaire