Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Golang program that uses func with variable argument list

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In Golang, a function that can be called with a variable argument list is known as a variadic function. One can pass zero or more arguments in the variadic function. If the last parameter of a function definition is prefixed by ellipsis …, then the function can accept any number of arguments for that parameter.

Syntax of a variadic function:

func f(elem ...Type)

Here ... operator tells Golang program to store all arguments of Type in elem parameter. After that, Go create an elem variable of the type []Type. Therefore, all the values passed are stored in an elem parameter which is a slice. A slice can also be passed in the argument instead of the argument list, as finally function is converting them into a slice.

For more information you can refer to Variadic Functions in Golang

Advantages of using a Variadic Function:

  • Passing a slice in a function is very easy.
  • Useful when the number of parameters is unknown.
  • Increases the readability of the program.

Let’s see some of the examples to use functions with variable argument list:

Example 1:




// Go program that uses a function
// with variable argument list
package main
  
// Importing required packages
import (
    "fmt"
)
  
// Variadic function to return 
// the sum of the numbers
func add(num ...int) int {
    sum := 0
    for j := range num {
        sum += j
    }
    return sum
}
  
func main() {
    fmt.Println("Sum =", add(1, 2, 3, 4, 5, 7, 8, 6, 5, 4))
}

Output:

Sum = 45

Example 2: A slice can also be used as an argument list.




// Go program that uses a function
// with variable argument list
// Using a slice as the argument list
package main
  
// importing required modules
import (
    "fmt"
)
  
// Function to check if an element
// is present in the list or not
func check(x int, v ...int) {
  
    flag := false
    index := 0
    for i, j := range v {
        if j == x {
            flag = true
            index = i
        }
    }
  
    if flag {
        fmt.Println("Element ", x, " found at index:", index)
    } else {
        fmt.Println("Element not present in the list")
    }
}
func main() {
    el := []int{1, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    check(1, el...)
    check(10, el...)
}

Output:

Element  1  found at index: 1
Element not present in the list

My Personal Notes arrow_drop_up
Last Updated : 10 May, 2020
Like Article
Save Article
Similar Reads