Find the minimum value in golang?

Viewed 17275

In the language there is a minimum function https://golang.org/pkg/math/#Min But what if I have more than 2 numbers? I must to write a manual comparison in a for loop, or is there another way? The numbers are in the slice.

3 Answers

General answer is: "Yes, you must use a loop, if you do not know exact number of items to compare".

In this package Min functions are implemented like:

// For 2 values
func Min(value_0, value_1 int) int {
    if value_0 < value_1 {
        return value_0
    }
    return value_1
}

// For 1+ values
func Mins(value int, values ...int) int {
    for _, v := range values {
        if v < value {
            value = v
        }
    }
    return value
}
Related