Reputation: 483
I know how to sort key/value with data type:
map[1:a 2:c 0:b]
using sort
package of GoLang. How can I sort a Pair
like the following:
[{c 2} {a 1} {b 0}]
I want the whole pair to be sorted either according to key or value? End result:
[{a 1} {b 0} {c 2}]
this is sorted according to keys. Below is sorted according to values:
[{b 0} {a 1} {c 2}]
Upvotes: 1
Views: 2359
Reputation: 188104
You could implement Len
, Swap
and Less
for a custom type. An example is given here: https://gobyexample.com/sorting-by-functions
Here's how you could sort by key for your example: http://play.golang.org/p/i6-e4I7vih
import (
"fmt"
"sort"
)
type Pair struct {
Key string
Value int
}
type ByKey []Pair
func (s ByKey) Len() int {
return len(s)
}
func (s ByKey) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s ByKey) Less(i, j int) bool {
return s[i].Key < s[j].Key
}
func main() {
pairs := []Pair{{"a", 1}, {"b", 0}, {"c", 2}}
// Sort by Key
sort.Sort(ByKey(pairs))
fmt.Println(pairs) // [{a 1} {b 0} {c 2}]
}
Upvotes: 4