Skip to content

Golang How to Calc Max Int Function (Slice or Any Number Input)

Let’s create a function that can accept multiple numbers and return the maximum number from them. In Golang, it is easy as pie and you can use variadic function definition for your maximum method:

Max(4, -5, 32, 2, 8) // direct numbers input
Max(numbers...) // the numbers variable is a slice of int = []int

Check this simple snippet and see how it works:

package main

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

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

	max, err := Max(numbers...)
	if err != nil {
		log.Fatal(numbers)
	}

	fmt.Println(max)

	max, _ = Max(4, -5, 32, 2, 8)

	fmt.Println(max)
}

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

	max := 0

	for _, num := range numbers {
		if num > max {
			max = num
		}
	}

	return max, nil
}

Leave a Reply

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