Go 泛型的草案截止今日已经基本定型了,与其他语言最大的不同应该就是 Go 的泛型利用 Interface 做 Constraint,可以说是与现有的 Interface 充分结合,之前的草案本来要引入新的关键字 contracts 在这次改动后被现有的 interface 代替,这使得 Interface 的概念更像 Rust 的 trait(实际上 Go 的泛型概念也与 Rust 相似),不过 Go 中实现 Interface 不需要显示声明,所以我想先谈一下 Interface 这个 Go 语言中最出色的“发明”。
Interface 实现了 Go 风格的 Duck typing
。它实现的方法查表方式与其他语言有些不同,有方法的语言大概有两个阵营
- C++ 和 Java 在编译时生成方法的静态方法表,比如 C++ 的 vtable
- Js 和 Python 动态查询,并花式缓存