-
-
Notifications
You must be signed in to change notification settings - Fork 490
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
mathutil.Max bug #292
Comments
If we follow the function signature of the standard library 1.21+, Should we change it this way? Or would it be more elegant to throw a panic when the number of arguments passed is zero? @duke-git |
@cannian1, There is no more elegant way to solve this problem, we can choose one of the following 4 methods. Each one has its drawbacks. I prefer the option 4 (last one).
func Max[T constraints.Integer | constraints.Float](numbers ...T) T {
if len(numbers) == 0 {
var zero T
return zero
}
max := numbers[0]
for _, v := range numbers {
if max < v {
max = v
}
}
return max
}
func Max[T constraints.Integer | constraints.Float](numbers ...T) (T, error) {
if len(numbers) == 0 {
var zero T
return zero, fmt.Errorf("no numbers")
}
max := numbers[0]
for _, v := range numbers {
if max < v {
max = v
}
}
return max, nil
}
func Max[T constraints.Integer | constraints.Float](numbers ...T) T {
if len(numbers) == 0 {
panic("mathutil.Max: empty numbers")
}
max := numbers[0]
for _, v := range numbers {
if max < v {
max = v
}
}
return max
} |
if numbers is empty,it will panic
The text was updated successfully, but these errors were encountered: