注:本文已Go SDK v1.18进行讲解
type any = interface{}
any,这实际上是 interface{} 的别名
package main
import (
"fmt"
)
func test(x any) any {
return x
}
func main() {
fmt.Println(test("a"))
//输出: a
}
之所以引入 any 关键字,主要是让泛型修饰时短一点,少一些括号。any 比 interface{} 会更清爽~
package main
import (
"fmt"
)
func Print[T interface{}](s ...T) {
for _, v := range s {
fmt.Print(v)
}
}
func main() {
Print("Hello, ", "playground\n")
//输出:Hello, playground
}
package main
import (
"fmt"
)
func Print[T any](s ...T) {
for _, v := range s {
fmt.Print(v)
}
}
func main() {
Print("Hello, ", "playground\n")
//输出:Hello, playground
}