Generic Min and Max With Constraints

Write generic min and max helpers constrained to ordered types, avoiding duplication across numeric and string collections.

GoData Integrity

Code

gosnippet
31 lines
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

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. Every import resolves inside the standard library — `cmp`.