How to Find the Maximum Integer Value In a GoLang Slice

How to Find the Maximum Integer Value In a GoLang Slice

Learn to Find the Maximum Integer Value In a GoLang Slice

You need to find the maximum integer in a Go slice. How would you do it?

Solution

This is the solution I wrote for Ardan Labs Training Kit:

package max

import "fmt"

// Max returns the maximum integer in the slice.
func Max(n []int) (int, error) {

	// First check there are numbers in the collection.
	if len(n) == 0 {
		return 0, fmt.Errorf("slice %#v has no elements", n)
	}

	// If the length of the slice is 1 then return the
	// integer at index 0.
	if len(n) == 1 {
		return n[0], nil
	}

	// Save the first value as current max and then loop over
	// the slice of integers looking for a larger number.
	max := n[0]
	for _, num := range n[1:] {

		// If num is greater than max, assign max to num.
		if num > max {
			max = num
		}
	}

	return max, nil
}

You can find the source code here: GoTraining

Did you like it? Why don't you try also...

How to remove the last character of a string in Golang

How to remove the last character of a string in Golang

Learn how to remove the last character of a string in GoLang

Is String a Palindrome?

Is String a Palindrome?

Learn How to Test if a String is a Palindrome in Go.

How to Find the Minimum Integer Value In a GoLang Slice

How to Find the Minimum Integer Value In a GoLang Slice

Learn to Find the minimum Integer Value In a GoLang Slice