Search code examples
gonullreflect

How to check reflect.Value is nil or not?


I have this code:

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

I want to check if my error is nil, but in my code, it doesn't work cuz it has different types. I try to make like this :

reflect[1] == reflect.Value(reflect.ValueOf(nil))

So it has the same type but the value of reflect.Value(reflect.ValueOf(nil)) isn't nil, it is <invalid reflect.Value>.


Solution

  • Use .IsNil() to check whether the value that's stored in reflect.Value is nil.

    if result[1].IsNil() {
       fmt.Println("ok")
    }
    

    Or you can use .Interface() to get the actual value that's stored in reflect.Value and check whether this is nil.

    if result[1].Interface() == nil {
        fmt.Println("ok")
    }