How to Use the slices and maps Packages (Generic Standard Library)

Use the slices and maps packages to perform common operations like sorting, copying, and searching on Go slices and maps with generic functions.

The slices and maps packages provide generic functions to manipulate slices and maps without writing boilerplate loops. Import them and call the specific function you need, such as slices.Sorted to get a sorted list of keys or maps.Copy to duplicate a map.

import (
	"maps"
	"slices"
)

// Get sorted keys from a map
keys := slices.Sorted(maps.Keys(myMap))

// Copy a map
newMap := maps.Clone(myMap)

// Check if a slice contains a value
found := slices.Contains(mySlice, targetValue)