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
}
No. Since Go doesn't allow the implicit conversion of types within slices (there is also no covariance with interfaces), you need to supply the appropriate methods for your type.
type MyObjects []MyObject
func (p MyObjects) Len() int { return len(p) }
func (p MyObjects) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p MyObjects) Less(i, j int) bool { return p[i] < p[j] }
If you really want to do this, you could use unsafe (but please don't). I doubt those 3 extra lines of safe code are going to make that big a difference for you.
http://play.golang.org/p/d6ciFjjr2c
objects := []MyObject{"one", "two", "three", "four"}
sort.Strings(*(*[]string)(unsafe.Pointer(&objects)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With