英文:
Is it possible to know the type of return value of a function in Go?
问题
例如,我想做这样的事情:
package main
import (
"fmt"
"reflect"
)
func main() {
var f func(int) int
v := reflect.ValueOf(f)
fmt.Println(v.ReturnType() == reflect.TypeOf(1)) // => true
}
reflect 包中不存在 ReturnType 方法。
我的问题是,我能否在不使用 cgo 的情况下实现这样的函数?
英文:
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.
答案1
得分: 6
不要使用reflect.ValueOf(f),而是使用reflect.TypeOf(f)。Type类型有两个相关的方法,分别是NumOut和Out(int)。为了按顺序获取所有返回值的类型,你可以使用以下循环:
typ := reflect.TypeOf(f)
for i := 0; i < typ.NumOut(); i++ {
returnType := typ.Out(i)
// 对returnType进行操作
}
如果你确定你的函数只有一个返回值,你可以使用Out(0)来获取它,但请确保你的输入是正确的。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论