Go 如何根据参数类型获取返回值?
当我定义函数时Go 如何根据参数类型获取返回值?,go,Go,当我定义函数时 func test(a int, b int) int { //bla } 我必须设置参数和返回值类型。如何基于参数类型返回值,例如 func test(argument type) type { //if argument type == string, must return string //or else if argument int, must return integer } 我可以这样做吗?如何做?Go缺少泛型(不以任何方式争论这一点)
func test(a int, b int) int {
//bla
}
我必须设置参数和返回值类型。如何基于参数类型返回值,例如
func test(argument type) type {
//if argument type == string, must return string
//or else if argument int, must return integer
}
我可以这样做吗?如何做?Go缺少泛型(不以任何方式争论这一点),您可以通过将接口{}
传递给函数,然后在另一端执行类型断言来实现这一点
package main
import "fmt"
func test(t interface{}) interface{} {
switch t.(type) {
case string:
return "test"
case int:
return 54
}
return ""
}
func main() {
fmt.Printf("%#v\n", test(55))
fmt.Printf("%#v", test("test"))
}
您必须键入并断言您得到的值
v := test(55).(int)
Go还没有像C#或Java这样的泛型。 它确实有一个空接口(接口{}) 如果我理解正确,我相信以下代码可以回答您的问题: 包干管
import (
"fmt"
"reflect"
)
type generic interface{} // you don't have to call the type generic, you can call it X
func main() {
n := test(10) // I happen to pass an int
fmt.Println(n)
}
func test(arg generic) generic {
// do something with arg
result := arg.(int) * 2
// check that the result is the same data type as arg
if reflect.TypeOf(arg) != reflect.TypeOf(result) {
panic("type mismatch")
}
return result;
}