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

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

Solution

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

package min

import "fmt"

// Min returns the minimum integer in the slice.
func Min(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 min and then loop over
	// the slice of integers looking for a smaller number.
	min := n[0]
	for _, num := range n[1:] {

		// If num is less than min. Assign min to num.
		if num < min {
			min = num
		}
	}

	return min, 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.

Go Strings Cheat Sheet Part 1

Go Strings Cheat Sheet Part 1

Learn the Basic of Working with GoLang Strings.