Example of Go variadic function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| func main() {
nums := []int{1, 2, 3}
// uses the existing slice
s1 := sum(nums...)
// creates a new slice
s2 := sum(1, 2, 3)
// Both s1 and s2 values are equal
// Variadic func can be called with no argument
s3 := sum()
}
func sum(nums ...int) (total int) {
for _, n := range nums {
total += n
}
}
|
The common example is the Println
function from the fmt
package.
1
| func Println(a ...interface{}) (n int, err error)
|