type MyObject string
var objects []MyObject
I want to sort these objects. The standard library has sort.Strings
, but that requires an instance of []string
instead of []MyObject
.
My current solution is to implement sort.Interface
(as shown below) and use sort.Sort
, but I'd like to get rid of that boilerplate code. Is there a nicer way?
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
}