【发布时间】:2015-11-18 07:13:12
【问题描述】:
type MyObject string
var objects []MyObject
我想对这些对象进行排序。标准库有sort.Strings,但这需要[]string 的实例而不是[]MyObject。
我目前的解决方案是实现sort.Interface(如下所示)并使用sort.Sort,但我想摆脱那个样板代码。有更好的方法吗?
type MyObjects []MyObject
func (objs MyObjects) Len() int {
return len(objs)
}
func (objs MyObjects) Less(i, j int) bool {
return strings.Compare(string(objs[i]), string(objs[j])) < 0
}
func (objs MyObjects) Swap(i, j int) {
o := objs[i]
objs[i] = objs[j]
objs[j] = o
}
【问题讨论】:
-
顺便说一句,
strings.Compare的文档明确指出您通常不应该使用它;就做return objs[i] < objs[j](或者如果抱怨,然后将它们投给string)。 -
另外,惯用的
Swap将是:func (p MyObjects) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -
有了这些简化,idiomatic way of doing it 一点也不差。
-
经验教训:我需要写更多的 Go 才能变得更地道。