如何使用反射在 Go 中查找空结构值?

我一直在寻找并为此苦苦挣扎了一段时间。我发现了另一个 Stack Overflow 问题,它让我朝着正确的方向前进但没有用:Quick way to detect empty values via reflection in Go

我当前的代码如下所示:

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)

    }

}

然而,我fmt.Printf打印出了 theval和reflect.ZeroI have,即使它们相同,它仍然进入语句if并且每个字段都被读取为非零,即使显然不是这种情况。我究竟做错了什么?我不需要更新字段,如果它们不为零,只需将它们添加到切片值中。


噜噜哒
浏览 90回答 1
1回答

隔江千里

对于初学者,如果IS为零值,则添加val到切片中,如果不是,则不添加。所以你应该检查而不是你有什么。除此之外,您的代码似乎工作正常:valuesval if !reflect.DeepEqual(...package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "reflect")type User struct {&nbsp; &nbsp; Name&nbsp; string&nbsp; &nbsp; Age&nbsp; &nbsp;int&nbsp; &nbsp; Email string}func main() {&nbsp; &nbsp; user, values := User{Name: "Bob", Age: 32}, []interface{}(nil)&nbsp; &nbsp; structIterator := reflect.ValueOf(user)&nbsp; &nbsp; for i := 0; i < structIterator.NumField(); i++ {&nbsp; &nbsp; &nbsp; &nbsp; field := structIterator.Type().Field(i).Name&nbsp; &nbsp; &nbsp; &nbsp; val := structIterator.Field(i).Interface()&nbsp; &nbsp; &nbsp; &nbsp; // Check if the field is zero-valued, meaning it won't be updated&nbsp; &nbsp; &nbsp; &nbsp; if !reflect.DeepEqual(val, reflect.Zero(structIterator.Field(i).Type()).Interface()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fmt.Printf("%v is non-zero, adding to update\n", field)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values = append(values, val)&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出以下内容(Go Playground Link):Name is non-zero, adding to updateAge is non-zero, adding to update因此,正确地看到该Email字段未初始化(或更正确地,包含 的零值string)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go