我们在学习Go语言的泛型时会经常使用 interface{} / any来替代所有的数据类型,除此之外我们还可以使用comparable 关键字来指代golang中所有可以用!=或者==来进行比较的元素。我们可以先查看comparable 的源码。
// comparable is an interface that is implemented by all comparable types
// (booleans, numbers, strings, pointers, channels, arrays of comparable types,
// structs whose fields are all comparable types).
// The comparable interface may only be used as a type parameter constraint,
// not as the type of a variable.
type comparable interface{ comparable }
这段话中定义了,布尔值、数字值、字符串、指针、通道、数组以及所有字段都相同的结构体属于comparable 类型。
comparable 比较容易引起误解的一点是很多人容易把他与可排序搞混淆。可比较指的是 可以执行 != == 操作的类型,并没确保这个类型可以执行大小比较( >,<,<=,>= )
- Comparable:可以使用 == 和 != 比较ÿ

最低0.47元/天 解锁文章
367

被折叠的 条评论
为什么被折叠?



