Comparable

Go1.18 comparable

April 22, 2022
Go
Comparable

Go 1.18 预定义接口类型 # 先看一个提案: proposal: spec: permit values to have type “comparable” – 允许值拥有comparable类型,我的理解是,现在的comparable只能用作泛型里的类型参数的约束,不能像普通类型那样使用,如下: type Set[E comparable] []E // 可以用做类型参数的约束 // 使用go1.18编译,报错:interface is (or embeds) comparable var A comparable // 变量不可以使用`comparable`类型 那么,结合例子就能更好地理解这个提案了。 这个提案的主要目的就是让例子里的var A comparable成立,也就是允许comparable作为变量的类型,跟其它普通的接口类型(var E error)一样。 // proposal: spec: permit values to have type "comparable" // As part of adding generics, Go 1.18 introduces a new predeclared interface type comparable. That interface type is implemented by any non-interface type that is comparable, and by any interface type that is or embeds comparable. ...