Think about it. How to check if reflect.Type is error type?

I need to make sure to check if the reflection .Type is an error.

Unable to reflect error. What is the formal / idiomatic way to check for type error in go reflect?

Go to playground Complete example

//return map of default values, based on each return type of a function
// error  => err=nil
// bool   => true
// struct => new struct
func getDefaultValue(originalFunction interface{}) map[int]reflect.Value {
    defaultValues := make(map[int]reflect.Value)

    typeOfFunc := reflect.ValueOf(originalFunction).Type()

    numOut := typeOfFunc.NumOut() //number of function returns

    for i := 0; i < numOut; i++ {

        typeOut := typeOfFunc.Out(i) // type of return for index i
        switch typeOut.Kind() {

        case reflect.Bool:
            defaultValues[i] = reflect.ValueOf(true)

        case reflect.Struct:
            defaultValues[i] = reflect.New(typeOut()).Elem()

        // --> How to identify reflect.Type error assuredly, using switch or if...
        //case reflect.error: //don't exists
        //  var err error = nil
        //  defaultValues[i] = reflect.ValueOf(&err).Elem()

        default:
            //var err error = nil
            //defaultValues[i] = reflect.ValueOf(&err).Elem()
            fmt.Println("type of return index ", i, " was not identified")

        }

        fmt.Println("type of return index ", i, typeOut, "kind", typeOut.Kind(), "assign to err ", typeOut.AssignableTo(reflect.TypeOf(errors.New(""))))
    }

    return defaultValues
}

      

+3


source to share


2 answers


Go error

is nothing special. error

is just a predefined interface type, so it doesn't have its own Kind in reflection. Try something:



errorInterface  := reflect.TypeOf((*error)(nil)).Elem()
...
case reflect.Interface:
    if typOute.Implements(errorInterface)  // it an error

      

+9


source


You can also just use the type name.



0


source







All Articles