Translate this page

Get Sorted Keys From Map In Go Using Generics 🔗

This is how to implement a generic function that returns the sorted keys from a map in the Go language.

See the blog post and the updated design draft. In particular the examples about map keys and sort.

package main

import (
  "fmt"
  "sort"
)

type Ordered interface {
  type int, int8, int16, int32, int64,
    uint, uint8, uint16, uint32, uint64,
    uintptr, float32, float64, string
}

type orderedSlice(type T Ordered) []T

func (s orderedSlice(T)) Len() int {
  return len(s)
}

func (s orderedSlice(T)) Less(i, j int) bool {
  return s[i] < s[j]
}

func (s orderedSlice(T)) Swap(i, j int) {
  s[i], s[j] = s[j], s[i]
}

func OrderedSlice(type T Ordered)(s []T) {
  sort.Sort(orderedSlice(T)(s))
}

func SortedKeys(type K Ordered, V interface{})(
    m map[K]V) []K {
  r := make([]K, 0, len(m))
  for k := range m {
    r = append(r, k)
  }
  OrderedSlice(r)
  return r
}

func main() {

  fmt.Println(
    SortedKeys(map[int]int{1: 2, 2: 4}))
  // Result: [1 2]

  fmt.Println(
    SortedKeys(
      map[string]int{"foo": 2, "bar": 4}))
  // Result: [bar foo]

}

Click to run this on the Go playground.


Download my free ebook


Subscribe to my mailing list and get a free email course

* indicates required

Interests



Translate this page

Updated on 2020 Jun 20.

DISCLAIMER: This is not professional advice. The ideas and opinions presented here are my own, not necessarily those of my employer.