Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort Go slices whose element type is an alias of string, but not string itself?

Tags:

types

sorting

go

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
}
like image 247
Stefan Majewsky Avatar asked Oct 23 '25 16:10

Stefan Majewsky


1 Answers

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)))
like image 165
JimB Avatar answered Oct 26 '25 08:10

JimB