golang implements the sorting example using the sort interface

  • 2020-06-01 09:58:58
  • OfStack

This article demonstrates an example of how golang implements ordering using the sort interface. I will share it with you for your reference as follows:

Today, I saw the implementation of sort and Interface again in the group. I couldn't make it with children's shoes 1, so I just started 1. Oh, yeah, the code is here.

The sort.Interface excuse has three methods, implement the three methods for your struct, and then do the sorting by passing your own structure to the sort.Sort method.

Of course, the sort package also has several common methods: sort.Float64Slice sort.IntSlise sort.StringSlise, hehe

package main
import (
type MapSorter []Item
type Item struct {
    Key string
    Val int64
func NewMapSorter(m map[string]int64) MapSorter {
    ms := make(MapSorter, 0, len(m))
    for k, v := range m {
        ms = append(ms, Item{k, v})
    return ms
func (ms MapSorter) Len() int {
    return len(ms)
func (ms MapSorter) Less(i, j int) bool {
    return ms[i].Val < ms[j].Val // According to the value of the sorting
    //return ms[i].Key < ms[j].Key // The key sorting
func (ms MapSorter) Swap(i, j int) {
    ms[i], ms[j] = ms[j], ms[i]
func main(){
    m  := map[string]int64 {
        "e": 10,
        "a": 2,
        "d": 15,
        "c": 8,
        "f": 1,
        "b": 12,
    ms := NewMapSorter(m)
    for _, item := range ms {
        fmt.Printf("%s:%d\n", item.Key, item.Val)

I hope this article has been helpful to you in the programming of Go language.

Related articles: