Reputation: 1043
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
}
ReturnType
method doesn't exist in reflect package.
My question is, can I implement such a function without using cgo
.
Upvotes: 4
Views: 1006
Reputation: 22196
Rather than using reflect.ValueOf(f)
try reflect.TypeOf(f)
. The Type
type has two relevant methods named NumOut
and Out(int)
. To get the types of 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're certain your function only has one return value, you can always get it with Out(0)
, the standard disclaimers about making sure your input is correct apply.
Upvotes: 6