英文:
Comparison And Ordering in Go
问题
在Go语言中,有没有内部机制来实现相等性和排序?(这样我们就可以在类型上使用比较运算符 - ==,!=,<,>,<=,>=。)
注意:我看到一些类型有一个名为Less的方法,似乎用于排序。但我找不到关于它或相等性检查接口的文档(如果有的话)。
英文:
Is there any internal mechanism in Go for implementing equality and ordering? (So we can use comparison operators on the type - ==, !=, <, >, <=, >=.)
Note: I saw some types have a method named Less which seems to be used for ordering. But I can not find the documentation for that or for equality checking interface (if there is any).
答案1
得分: 7
Go不支持运算符重载,因此您无法使用您的类型覆盖这些运算符的行为。如果您需要在您的类型上使用这些操作,则将它们定义为方法。
您可能在某些类型上看到的Less
方法可能是作为sort.Interface
接口的一部分,或者可能是heap.Interface
(它扩展了排序接口)。
英文:
Go does not support operator overloading, so you won't be able to override the behaviour of those operators with your type. If you need to use those operations on your type, then define them as methods.
The Less
method you may have seen on some types is probably there as part of the sort.Interface
interface or possibly heap.Interface
(which extends the sort interface).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论