VOOZH about

URL: https://www.geeksforgeeks.org/go-language/variadic-functions-in-go/

⇱ Variadic Functions in Go - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Variadic Functions in Go

Last Updated : 25 Oct, 2024

Variadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you don’t know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including none.

Example:


Output
Sum of 1, 2, 3: 6
Sum of 4, 5: 9
Sum of no numbers: 0

Syntax

func functionName(parameters ...Type) ReturnType {
// Code
}

In the syntax above:

  • parameters ...Type indicates that the function can accept a variable number of arguments of type Type.
  • You can access the arguments within the function as a slice.

Using Variadic Functions

When defining a variadic function, you specify the type of the arguments followed by an ellipsis (...) as shown in the above example. Inside the function, these arguments can be treated as a slice.

Calling a Variadic Function

You can call a variadic function with any number of arguments, including zero. The function treats the arguments as a slice.

Example:


Output
Sum of 1, 2, 3: 6
Sum of 4, 5: 9
Sum of no numbers: 0

Variadic Functions with Other Parameters

You can also mix variadic parameters with regular parameters in a function. The variadic parameter must always be the last parameter.

Example:


Output
Sum of numbers:
Number: 1
Number: 2
Number: 3
Another sum:
Number: 4
Number: 5
No numbers sum:

Limitations of Variadic Functions

  • Variadic functions can only have one variadic parameter, and it must be the last parameter.
  • You cannot have multiple variadic parameters in a single function definition.
Comment
Article Tags:

Explore