我正在尝试检查结构中的字段是否使用 reflect.DeepEqual
设置为零值。这个想法是,如果是这种情况,我可以使用作为结构标记给出的默认值来更改其值,如下所示:
type struct {
A int `default:"42"`
}
我的问题如下:看起来reflect.DeepEqual
总是返回我false
。我想我错过了一些东西。这是我正在尝试做的一个简单示例:
package main
import (
"fmt"
"reflect"
)
func main() {
s := struct{ A int }{0}
field := reflect.ValueOf(s).Field(0)
fmt.Println(field.Interface())
fmt.Println(reflect.Zero(field.Type()))
fmt.Println(reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type())))
}
这是上面代码的 go Playground 版本:https://play.golang.org/p/k9VY-2Dc69
我想知道为什么 DeepEqual
在这种情况下返回 false
。
谢谢!
最佳答案
这里:
reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()))
您正在将 int
值(封装在 interface{}
中)与 reflect.Value
类型的值进行比较。 reflect.Zero()
返回 reflect.Value
类型的值,而不是 interface{}
。
您忘记调用Value.Interface()
关于第二个参数:
reflect.DeepEqual(field.Interface(), reflect.Zero(field.Type()).Interface())
这会打印true
。试试 Go Playground .
关于golang DeepEqual 和 Reflect.Zero,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42511940/