2

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>.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Zouglou
  • 89
  • 1
  • 11
  • To get the actual value that's stored in `reflect.Value` you can use the `.Interface()` method. https://play.golang.com/p/42fVZLqYtV3. The docs: https://golang.org/pkg/reflect/#Value.Interface – mkopriva Apr 06 '20 at 12:36

1 Answers1

7

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")
}
gabetucker22
  • 118
  • 7
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • The instruction `fmt.Println(reflect.ValueOf(nil).IsNil())` result in a panic displaying the message "panic: reflect: call of reflect.Value.IsNil on zero Value". Strangely, the method call IsZero() also panics with the message "panic: reflect: call of reflect.Value.IsZero on zero Value". Once I have a reflect.Value of nil, it seam that there is no test to detect this. – chmike Jun 01 '23 at 18:38
  • you may use `reflect.ValueOf(nil).IsValid()` which, given the doc, `returns false if v is the zero Value.` – vincent-tr Jun 15 '23 at 08:25