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

snippet
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
}