Generic Min and Max With Constraints
Write generic min and max helpers constrained to ordered types, avoiding duplication across numeric and string collections.
Code
package collection
import "cmp"
func Min[T cmp.Ordered](values []T) (T, bool) {
var zero T
if len(values) == 0 {
return zero, false
}
best := values[0]
for _, value := range values[1:] {
if value < best {
best = value
}
}
return best, true
}
func Max[T cmp.Ordered](values []T) (T, bool) {
var zero T
if len(values) == 0 {
return zero, false
}
best := values[0]
for _, value := range values[1:] {
if value > best {
best = value
}
}
return best, true
}What the code does
Repetition is confined to for _, value := range values[1:] — the rest of the file is straight-line.
What to watch for
- Each symbol used is a language built-in — nothing has to be fetched.
Statements that carry the weight
for _, value := range values[1:] {
if value < best {
best = value
}
}
for _, value := range values[1:] {
if value > best {
best = value
}
}
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.Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Every import resolves inside the standard library — `cmp`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.