Max
, minSuppose you have 2 values and want to find out which one is higher or lower than the other. The max()
and min built-ins in Go can be used for this purpose.
For slices, we cannot use max and min, but we can use the slices package and its generic methods slices.Max
and slices.Min
. These methods return the highest or lowest element in a slice.
This program uses the min, max, and slices.Min
and slices.Max
methods in various ways. For slices, we must use the slices package methods.
min()
built-in on 2 int
values. This gives the result of 10, which is less than the other value 20.Max
meanwhile return the higher (or highest) number in the argument list. Here it returns 20 instead of 10.Max
and min can be used with more than 2 arguments—the highest or lowest of all the arguments is returned.max()
and min()
directly. But we can use the slices.Max
and slices.Min
methods.package main import ( "fmt" "slices" ) func main() { // Part 1: use min with 2 int values. left := 10 right := 20 result := min(left, right) fmt.Println("min", result) // Part 2: use max. result2 := max(left, right) fmt.Println("max", result2) // Part 3: use min with 3 string values. result3 := min("coffee", "bold", "actual") fmt.Println("min", result3) // Part 4: use slices.Min and slices.Max on an int slice. values := []int{10, 20, 0, 100} result4 := slices.Min(values) fmt.Println("slices.Min", result4) result5 := slices.Max(values) fmt.Println("slices.Max", result5) }min 10 max 20 min actual slices.Min 0 slices.Max 100
Though finding the highest or lowest value can be accomplished with an if
-check in a for
-loop, max()
and min require less code. This leads to code that is easier to maintain.