search

Explain the use of Go's variadic functions for handling variable-length argument lists?

In Go, a function can take a variable number of arguments using a feature called "variadic functions". A variadic function is defined using an ellipsis () before the type of the last parameter in the function signature, indicating that the function can accept zero or more arguments of that type.

For example, the following function **sum** takes a variable number of **int** arguments and returns their sum:

func sum(nums ...int) int {
    total := 0
    for _, num := range nums {
        total += num
    }
    return total
}

You can call the **sum** function with any number of **int** arguments:

sum()              // returns 0
sum(1)             // returns 1
sum(1, 2)          // returns 3
sum(1, 2, 3)       // returns 6
sum(1, 2, 3, 4, 5) // returns 15

Within the function body, the **nums** parameter is treated as a slice of **int** values, so you can use all the standard slice operations to manipulate the arguments.

Variadic functions are commonly used in Go for functions that need to accept a variable number of arguments, such as **fmt.Printf** which takes a format string followed by a variable number of arguments to format according to the format string.

Related Questions You Might Be Interested