如何检查reflect.Value是否为零?

Zou*_*lou 0 null go reflect

我有这个代码:

package main

import (
    "fmt"
    "reflect"
)


type cmd struct{
    Echo func(string) (string,error)
}



func main() {
    cmd := cmd{
        Echo : func(arg string) (string, error) {
            return arg, nil
        },
    }
    result := reflect.ValueOf(cmd).FieldByName("Echo").Call([]reflect.Value{reflect.ValueOf("test")})
    if result[1] == nil{
        fmt.Println("ok")
    }
}
Run Code Online (Sandbox Code Playgroud)

我想检查我的错误是否为零,但在我的代码中,它不起作用,因为它有不同的类型。我试着做这样的:

reflect[1] == reflect.Value(reflect.ValueOf(nil))
Run Code Online (Sandbox Code Playgroud)

所以它具有相同的类型,但 的值reflect.Value(reflect.ValueOf(nil))不是 nil,而是<invalid reflect.Value>

Ekl*_*vya 5

使用.IsNil()检查中所储存的值reflect.Valuenil或不是。

if result[1].IsNil() {
   fmt.Println("ok")
}
Run Code Online (Sandbox Code Playgroud)

或者您可以使用.Interface()来获取存储在其中的实际值reflect.Value并进行检查。感谢@mkopriva 指出。

if result[1].Interface() == nil {
    fmt.Println("ok")
}
Run Code Online (Sandbox Code Playgroud)