Home
Go
max and min (Get Highest or Lowest Value)
Updated Jan 2, 2025
Dot Net Perls
Max, min. Suppose 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.
slices.Contains
Example. 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.
Part 1 We use the min() built-in on 2 int values. This gives the result of 10, which is less than the other value 20.
Part 2 Max meanwhile return the higher (or highest) number in the argument list. Here it returns 20 instead of 10.
Part 3 Max and min can be used with more than 2 arguments—the highest or lowest of all the arguments is returned.
Part 4 For slices, we cannot use 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 2, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen