Go core
Browse topics

min, max, and clear

Version
1.27
Since
1.21
Review
Draft

Summary#

min and max select an extreme from ordered values. clear removes all entries from a map or sets the current elements of a slice to their type's zero value.

Syntax#

go
lowest := min(a, b)
highest := max(a, b)
clear(values)
clear(counts)

Example#

go
package main

import "fmt"

func main() {
	fmt.Println(min(4, 9, 2), max(4, 9, 2))

	stocks := map[string]int{"pear": 3}
	counts := []int{5, 8}
	clear(stocks)
	clear(counts)

	fmt.Println(len(stocks), counts)
}

Expected output#

Text
2 9
0 [0 0]

Common mistakes#

Clearing a slice preserves its length and capacity. To reuse the buffer with no elements, reslice it to length zero after clearing. Pass individual arguments to min or max. Either returns NaN if any floating-point argument is NaN.

Version applicability#

All three built-ins and the example require Go 1.21. On earlier versions, compute extremes with comparisons and handle NaN explicitly when needed. Use loops to delete map keys or zero slice elements.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0