Source: blog.boot.dev

How to Sort a Slice in Go
Sorting is a common task in programming, and for that reason, most languages have a default sorting algorithm in their standard library. type Interface interface { // Len is the number of elements in the collection. Len() int // Less reports whether the element with // index i should sort before the element with index j.

Let’s sort a slice of structs: type mtgCard struct { manaCost int name string } type mtgCards []mtgCard Now we implement the sorting: func (mCards mtgCards) Len() int { return len(mCards)} func (mCards mtgCards) Less(i, j int) bool { if mCards[i].manaCost < mCards[j].manaCost { return true } else if mCards[i].manaCost == mCards[j].manaCost { return mCards[i].name < mCards[j].name

Related Articles