我如何对某物(如何比较两个切片)进行分类
可以比较两个字符串:
package main
func main() {
println("ab" > "ba")
println("ab" < "ba")
}
false
true
Program exited.
https://go.dev/play/play/pplay/p/svklf6r84sc
如何在两个切片上执行类似的操作?例如[] int {1,2}&gt; [] int {2,1}
。
我需要将其排序一片ints。因此,我需要实现sort.interface
。
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
如果此实现是通用的,那就更好了。
In Go is possible to compare two strings:
package main
func main() {
println("ab" > "ba")
println("ab" < "ba")
}
false
true
Program exited.
https://go.dev/play/p/svkLf6R84SC
How do I perform a similar operation on two slices? e.g. []int{1,2} > []int{2,1}
.
I need this to sort a slice of slices of ints. So I need an implementation of sort.Interface
.
type Interface interface {
Len() int
Less(i, j int) bool
Swap(i, j int)
}
It would be better if this implementation is generic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写比较器和
sort.slices
的功能较小的功能是在标准库中执行此操作的最有效方法。稍微逐步踩到该(直到标准库中的仿制用法最终确定),在GO 1.18中,我们可以使用
golang.org/x/exp/constraints
and code> golang.org/x/ EXP/SLICES jackages通常要排序有序值的切片: https:// go。 dev/play/p/p/ma0ly6povfr关于
slices .compare
:Writing a comparator and a less function for
sort.Slices
would be the most effective way to do this within the standard library.Stepping outside of that slightly (until generics usage within the standard library is finalized), in Go 1.18 we can use the
golang.org/x/exp/constraints
andgolang.org/x/exp/slices
packages to generically sort a slice of slices of ordered values: https://go.dev/play/p/MA0lY6POVFRDocumentation about
slices.Compare
: