package main
import (
"fmt"
)
func findMinMax[T comparable](arr []T) (min, max T) {
for _, v := range arr {
if v > max {
max = v
} else if v < min {
min = v
}
}
return min, max
}
func main() {
arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9}
fmt.Println(findMinMax(arr))
}
I would be more than happy to help you resolve the issue you are facing in the findMinMax function. The error message indicating that v > max or v < min suggests that there might be a problem with the comparison operation within the function. In order to offer a precise solution, I would need to see the implementation of the findMinMax function. Based on your description, it seems that the type T, which is supposed to be comparable, is causing the issue during comparison.
I am expecting the function findMinMax will work correctly.
You used the
comarableconstraint for theTtype parameter.comparablemeans that: comparable. So you can use the==operator on values of that type. It doesn't mean they are ordered, which is required to use the<>operators.The ordered constraint is defined in the
golang.org/x/exp/constraintspackage, seeconstraints.Ordered.Using that your code compiles:
Try it on the Go Playground.
It gives wrong result though, as you're starting
minandmaxfrom their zero values, and if all values in the passed slice are greater than or less than the zero value,minormaxwill remain the zero value.An easy fix is to initialize
minandmaxwith the first value if the passed slice is not empty:This will output (try it on the Go Playground):
Note if you're working with floating point types, you have to explicitly handle
NaNvalues as their order to other floats is not specified.