1

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()))
    }
}

Output:

 false
Some text false
sm4ll_3gg
  • 217
  • 4
  • 10

1 Answers1

3

you want to do

package main

import (
    "fmt"
    "reflect"
)

func main() {
    s := ""
    v := reflect.ValueOf(s)
    t := reflect.TypeOf(s)
    fmt.Println(v.Interface() == reflect.Zero(t).Interface()) // true

}

Just like the answer in the previous question and nothing else.

why?

To compare two Values, compare the results of the Interface method. Using == on two Values does not compare the underlying values they represent.

https://golang.org/pkg/reflect/#Value

mpm
  • 20,148
  • 7
  • 50
  • 55