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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does MinFunc MaxFunc Pick Struct Extremes print when run?
- The script runs standalone; its 3 labeled outputs include `cheapest:`, `priciest:`, `empty:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.