Generics Min Max With Type Constraints
Use Go generics with type constraints for type-safe min and max functions.
Code
package main
import ("fmt")
type Ordered interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 |
~float32 | ~float64 | ~string
}
func Min[T Ordered](a, b T) T {
if a < b { return a }
return b
}
func Max[T Ordered](a, b T) T {
if a > b { return a }
return b
}
func main() {
fmt.Println(Min(3, 5), Max(3.14, 2.71), Min("a", "b"))
}Mechanics of the run
Count the function main as the entire surface area of Generics Min Max With Type Constraints.
Core lines
func Min[T Ordered](a, b T) T {
if a < b { return a }
return b
}
func Max[T Ordered](a, b T) T {
if a > b { return a }
return b
}
func main() {
fmt.Println(Min(3, 5), Max(3.14, 2.71), Min("a", "b"))
}
Interactive Tools for This Topic
FAQ
- How do you run Generics Min Max With Type Constraints?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.