乐闻世界logo
搜索文章和话题

What is a variadic function in Go?

1个答案

1

Variadic functions are a special type of function that can accept an arbitrary number of parameters. In Go, variadic function parameters are identified by placing the ellipsis ... before the parameter type. These parameters are treated as slices within the function.

For example, consider a function that calculates the sum of an arbitrary number of integers. In Go, such a function can be defined as:

go
package main import "fmt" // Sum function accepts a variadic number of integer parameters func Sum(nums ...int) int { total := 0 for _, num := range nums { total += num } return total } func main() { sum := Sum(1, 2, 3, 4, 5) fmt.Println("Sum:", sum) }

In this example, we define a function named Sum that accepts a variadic parameter nums. This parameter exists as a slice within the function. We compute the cumulative sum of all elements by iterating through this slice and return the result.

Variadic functions are highly useful for handling an unspecified number of inputs, such as in logging, formatted output, and aggregation operations. Internally, the caller constructs an array and passes it as a slice to the function. Therefore, using variadic parameters does not incur additional performance overhead.

2024年8月7日 21:50 回复

你的答案