Skip to content

Get Minimum Number From a Slice In Golang

Finding a minimum number between a list of numbers is not hard but most of the min functions compare only between two numbers.

Here we have a function that can accept any number of input and returns the minimum value from them:

Min(9, 4, -5, 2, -8, 6)
Min(numbers...) // if you have a slice or array

Test it yourself to see the results:

package main

import (
	"errors"
	"fmt"
	"log"
)

func main() {
	numbers := []int{4, -2, 6, 0, 9, -2, 4}

	min, err := Min(numbers...)
	if err != nil {
		log.Fatal(numbers)
	}

	fmt.Println(min)

	min, _ = Min(9, 3, -6, 2, -4)

	fmt.Println(min)
}

func Min(numbers ...int) (int, error) {
	if len(numbers) == 0 {
		return 0, errors.New("input is empty")
	}

	min := 0

	for _, num := range numbers {
		if num < min {
			min = num
		}
	}

	return min, nil
}

Leave a Reply

Your email address will not be published. Required fields are marked *