What is the correct way to find the min between two integers in Go?
Solution 1:
Nope, I think writing something like that is fine: for instance, the stdlib's sort.go does it near the top of the file:
func min(a, b int) int {
if a < b {
return a
}
return b
}
math.Min(2, 3)
happened to work because numeric constants in Go are untyped. Beware of treating float64s as a universal number type in general, though, since integers above 2^53
will get rounded if converted to float64.
Although it does not work on stable Go as I'm writing this, in the Go 1.18 beta you can write a generic min
function which is just as efficient at run time as the hand-coded single-type version.
There's been discussion of updating the stdlib to add generic versions of existing functions, but if that happens it won't be until a later version.
Solution 2:
There is no built-in min or max function for integers, but it’s simple to write your own. Thanks to support for variadic functions we can even compare more integers with just one call:
func MinOf(vars ...int) int {
min := vars[0]
for _, i := range vars {
if min > i {
min = i
}
}
return min
}
Usage:
MinOf(3, 9, 6, 2)
Similarly here is the max function:
func MaxOf(vars ...int) int {
max := vars[0]
for _, i := range vars {
if max < i {
max = i
}
}
return max
}
Solution 3:
For example,
package main
import "fmt"
func min(x, y int) int {
if x < y {
return x
}
return y
}
func main() {
t := "stackoverflow"
v0 := make([]int, len(t)+1)
v1 := make([]int, len(t)+1)
cost := 1
j := 0
v1[j+1] = min(v1[j]+1, min(v0[j+1]+1, v0[j]+cost))
fmt.Println(v1[j+1])
}
Output:
1
Solution 4:
Though the question is quite old, maybe my package imath can be helpful for someone who does not like reinventing a bicycle. There are few functions, finding minimal of two integers: ix.Min
(for int
), i8.Min
(for int8
), ux.Min
(for uint
) and so on. The package can be obtained with go get
, imported in your project by URL and functions referred as typeabbreviation.FuncName
, for example:
package main
import (
"fmt"
"<Full URL>/go-imath/ix"
)
func main() {
a, b := 45, -42
fmt.Println(ix.Min(a, b)) // Output: -42
}