capypad
0 day streak
go / beginner
Snippet

Variadic Functions for Flexible Arguments

Variadic functions accept zero or more arguments using the `...T` syntax. Inside the function, the variable becomes a slice. You can also have required parameters before the variadic part. This pattern is useful for building flexible APIs.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package main
 
import "fmt"
 
 
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
 
func printNames(first string, others ...string) {
fmt.Printf("First: %s\n", first)
for _, name := range others {
fmt.Printf("Also: %s\n", name)
}
}
 
func main() {
fmt.Println("Total:", sum(1, 2, 3, 4, 5))
fmt.Println("Single:", sum(42))
fmt.Println("Empty:", sum())
printNames("Alice", "Bob", "Charlie")
}
Breakdown
1
func sum(numbers ...int) int
numbers becomes []int with all passed values
2
for _, n := range numbers
Iterate over the slice created by variadic
3
first string, others ...string
Required param before variadic, others is []string
4
sum(1, 2, 3, 4, 5)
Called with 5 arguments
5
sum()
Called with zero arguments, numbers is empty slice