Is it possible to know the return type of a function in Go?

For example, I want to do something like this,

package main

import (
    "fmt"
    "reflect"
)

func main() {
    var f func(int) int
    v := reflect.ValueOf(f)
    fmt.Println(v.ReturnType() == reflect.TypeOf(1)) // => true
}

ReturnTypeThe method does not exist in the reflection package. My question is: can I implement such a function without using cgo.

+4
source share
1 answer

reflect.ValueOf(f)Try instead reflect.TypeOf(f). A type Typehas two corresponding methods named NumOutand Out(int). To get all return values ​​in order, you can use the following loop

typ := reflect.TypeOf(f)

for i := 0; i < typ.NumOut(); i++ {
    returnType := typ.Out(i)
    // do something with returnType
}

If you are sure that your function has only one return value, you can always get it using Out(0)standard failures, make sure that your input is correct.

+6

All Articles