How to Use the maps and slices Packages from the Standard Library

The `maps` and `slices` packages are standard library utilities added in Go 1.21 to provide common operations on maps and slices without requiring external dependencies. Import them and use their exported functions directly on your data structures.

How to Use the maps and slices Packages from the Standard Library

The maps and slices packages are standard library utilities added in Go 1.21 to provide common operations on maps and slices without requiring external dependencies. Import them and use their exported functions directly on your data structures.

package main

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

func main() {
	// Copy a map
	src := map[string]int{"a": 1, "b": 2}
	dst := maps.Clone(src)
	fmt.Println("Cloned map:", dst)

	// Check if a key exists
	if maps.Has(src, "a") {
		fmt.Println("Key 'a' exists")
	}

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

	// Check if a slice contains a value
	if slices.Contains(nums, 4) {
		fmt.Println("Value 4 found")
	}
}