How to Use maps and slices Packages from Go Standard Library

Use the maps and slices packages in Go 1.21+ to easily sort, copy, and manipulate maps and slices with built-in utility functions.

The maps and slices packages provide standard utility functions for Go maps and slices, available since Go 1.21. Use maps.Keys to get a sorted list of keys and slices.Sort to order slice elements without writing custom loops.

package main

import (
	"fmt"
	"maps"
	"slices"
)

func main() {
	// Get sorted keys from a map
	m := map[string]int{"b": 2, "a": 1}
	keys := maps.Keys(m)
	slices.Sort(keys)
	fmt.Println(keys) // Output: [a b]

	// Sort a slice of integers
	nums := []int{3, 1, 4, 1, 5}
	slices.Sort(nums)
	fmt.Println(nums) // Output: [1 1 3 4 5]
}