Page

【Go】在Golang中使用interface实现泛型

468Anson20-02-20


在Golang中使用interface实现泛型
package main
import (
   "fmt"
   "reflect"
)
func TestInterface(v interface{}) interface{} {
    switch v.(type) {
        case int:
            // DO Something
            return v.(int) + 10
        case float64:
            // DO Something
            return v.(float64) + 22.3
    }
    return v
}
func main()  {
    t1 := TestInterface(10)
    t2 := TestInterface(10.0)
    fmt.Println(t1, reflect.TypeOf(t1).String())
    fmt.Println(t2, reflect.TypeOf(t2).String())
}

go run 输出:

20 int

32.3 float64



来自anson博客 

http://www.tp0.top