Go 如何确定函数返回的值的数量
如何获取函数的返回值长度,其效果类似于:Go 如何确定函数返回的值的数量,go,reflection,Go,Reflection,如何获取函数的返回值长度,其效果类似于: func Foo() (int, int){ ... } func Bar() (int, float, bool, string, error){ ... } n1 := getReturnLength(Foo) // shall be 2 n2 := getReturnLength(Bar) // shall be 5 如何实现getReturnLength函数或类似的功能?您可以使用reflect包实现它 reflect.Type
func Foo() (int, int){
...
}
func Bar() (int, float, bool, string, error){
...
}
n1 := getReturnLength(Foo) // shall be 2
n2 := getReturnLength(Bar) // shall be 5
如何实现getReturnLength函数或类似的功能?您可以使用reflect包实现它
reflect.TypeOf(Foo).NumOut()
您可以在这里了解reflect包您不应该使用reflection将函数的返回值放入片中。相反,您应该返回一个迭代结果范围的切片
package main
import (
"fmt"
)
func foo(num int) []int {
s := make([]int, num)
for i := 1; i <= num; i++ {
s[i-1] = i
}
return s
}
func main() {
r := foo(5)
// Will run 0 times if len(r) == 0
// Obviously, if you need 1+
// results, you need to guard this
// with something like
// if len(r) < 1...
for i := range r {
fmt.Printf("Hello, %d!\n", r[i])
}
// Or, simpler
for i, v := range foo(5) {
fmt.Printf("Index %d => Value %d\n", i, v)
}
}
或者我可以使用类似的方法来接收返回:go s:=make[]接口{},0 s..=Foo//现在它是无效的,或者换句话说,如何将函数的返回值打包到数组或切片中?反射可以做到这一点,但真正的问题是:为什么需要它?我想用这种方法编写一个常规的错误检查方法,而不是在每个函数调用中检查错误,也许更优雅一些,我不知道。