Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sort map

  • You can't really sort a map, but you can iterate over the keys in some sorted way.
  • You just need to fetch the keys, sort them, and then iterate over that slice.
package main

import (
	"fmt"
	"sort"
)

func main() {
	scores := map[string]int{"Alma": 23, "Cecilia": 12, "David": 37, "Berta": 78}
	fmt.Println(len(scores))
	fmt.Println(scores)
	fmt.Println()

	for name, score := range scores {
		fmt.Printf("%-7v %v\n", name, score)
	}
	fmt.Println()

	names := make([]string, 0, len(scores))
	for name := range scores {
		names = append(names, name)
	}
	fmt.Println(names)
	sort.Strings(names)
	fmt.Println(names)
	fmt.Println()

	for _, name := range names {
		fmt.Printf("%-7v %v\n", name, scores[name])
	}
}
4
map[Alma:23 Berta:78 Cecilia:12 David:37]

Cecilia 12
David   37
Berta   78
Alma    23

[Alma Cecilia David Berta]
[Alma Berta Cecilia David]

Alma    23
Berta   78
Cecilia 12
David   37