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 (

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) {

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)
  return r

func main() {

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

      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


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.