當我定義函數(shù)時func test(a int, b int) int { //bla}我必須設(shè)置參數(shù)和返回值類型。我如何根據(jù)參數(shù)類型返回值,例如func test(argument type) type { //if argument type == string, must return string //or else if argument int, must return integer}我可以這樣做嗎?
2 回答

森林海
TA貢獻2011條經(jīng)驗 獲得超2個贊
Go 還沒有像 C# 或 Java 這樣的泛型。它確實有一個空接口(interface{})
如果我理解正確,以下是我認為可以回答您的問題的代碼:
包主
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;
}
- 2 回答
- 0 關(guān)注
- 240 瀏覽
添加回答
舉報
0/150
提交
取消