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
}
PIPIONE
相关分类