现在 Go 将拥有泛型:Go将Interface{}替换为“Any” ,这是一个类型别名:
type any = interface{}
这会引入了泛型作好准备,实际上,带有泛型的Go 1.18 Beta 1
func doSomething[X interface{}, Y Fooer[interface{}]](v X, src Y) error { } |
使用any替代`interface{}`后就简洁:
func doSomething[X any, Y Fooer[any]](v X, src Y) error { } |
之前C++、Java、JavaScript、Python、Ruby、Rust都支持泛型,现在Golang也加入泛型支持。
15年前Java没有泛型支持时,代码是这么写的:
List /* |
使用注释注明集合类型,在Go 既没有泛型也没有联合类型情况下,Go可能会这么写:
type fileOps []any // []T where T is (string | int64) |
文章来源于互联网:Golang引入泛型:Go将Interface{}替换为“Any”