Passing variable number of arguments in a function

Follow the latest of Whizdumb’s journey here.

Continuing with our learning of functions in go, lets now explore how a function can accept variable number of arguments in a function.

Lets modify calculateMinimumAndMaximum(x []int) (int,int) from previous post to accept a variable number of arguments rather than an array or slice.

Lets update the function signature and definition first.

func calculateMinimumAndMaximum(x ...int) (min int, maximum int) {
    minimum := -1
    max := 0    
    for _, v := range x {
        if minimum == -1 || v < minimum {
          minimum = v
        }
        if max < v {
            max = v
        }
    }
    return minimum, max 
}


Here we have defined a function which accepts a variable number of arguments of type int. The functions are called Variadic functions

Now we can call this function with a variable number of arguments, all of which should be of type int.

Here is how the whole thing looks like.

package main

import "fmt"

func main() {      
    minimum, maximum := calculateMinimumAndMaximum(48,96,86,68,
    57,82,63,70,
    37,34,83,27,
    19,97, 9,17,)
    fmt.Println("Minimum value is", minimum)
    fmt.Println("Maximum value is", maximum)   
}

func calculateMinimumAndMaximum(x ...int) (min int, maximum int) {
    minimum := -1
    max := 0    
    for _, v := range x {
        
        if minimum == -1 || v < minimum {
        
          minimum = v
        }
        
        if max < v {
         
            max = v
        }
    }
    return minimum, max 
}

~~ Whizdumb ~~