MinFunc MaxFunc Pick Struct Extremes

MinFunc and MaxFunc take a comparator and return the smallest or largest struct without a natural ordering, falling back to the zero value on empty slices.

GoData Integrity

Code

gosnippet
34 lines
package main

import (
	"fmt"
	"slices"
)

type Sample struct {
	Label string
	Cents int
}

func main() {
	samples := []Sample{
		{Label: "edge", Cents: 120},
		{Label: "core", Cents: 90},
		{Label: "edge", Cents: 40},
		{Label: "api", Cents: 210},
	}

	// MinFunc/MaxFunc 接受比较器:结构体没有自然顺序时按字段选极值
	cheapest := slices.MinFunc(samples, func(a, b Sample) int {
		return a.Cents - b.Cents
	})
	priciest := slices.MaxFunc(samples, func(a, b Sample) int {
		return a.Cents - b.Cents
	})
	fmt.Println("cheapest:", cheapest.Label, cheapest.Cents)
	fmt.Println("priciest:", priciest.Label, priciest.Cents)

	// 空切片返回零值:调用方要防边界
	var empty []Sample
	fmt.Println("empty:", slices.MinFunc(empty, func(a, b Sample) int { return 0 }))
}

What the code does

MinFunc MaxFunc Pick Struct Extremes keeps everything in the function main.

Applying it

The demo output is labeled (cheapest:, priciest:, empty:), so every printed line maps back to its originating operation.

Statements that matter

return a.Cents - b.Cents

Interactive Tools for This Topic

FAQ

What does MinFunc MaxFunc Pick Struct Extremes print when run?
The script runs standalone; its 3 labeled outputs include `cheapest:`, `priciest:`, `empty:`.