capypad
0 day streak
go / beginner
Snippet

Variadic Functions: Flexible Argument Handling

Variadic functions accept any number of arguments of the same type. The ... syntax before the type parameter makes a function variadic. Inside the function, the variable is received as a slice. You can pass individual arguments or unpack a slice using the ... operator. This pattern is useful for logging, formatting, and utility functions.

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
27
28
29
30
31
32
33
34
35
36
37
package main
 
import "fmt"
 
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
 
func greet(greeting string, names ...string) {
for _, name := range names {
fmt.Printf("%s, %s!\n", greeting, name)
}
}
 
func combine(base string, parts ...string) string {
result := base
for _, part := range parts {
result += "|" + part
}
return result
}
 
func main() {
fmt.Println("Sum:", sum(1, 2, 3, 4, 5))
fmt.Println("Sum of no numbers:", sum())
 
greet("Hello", "Alice", "Bob", "Charlie")
 
fmt.Println("Combined:", combine("Start", "A", "B", "C"))
 
nums := []int{10, 20, 30}
fmt.Println("Slice sum:", sum(nums...))
}
Breakdown
1
func sum(numbers ...int) int
Declares a variadic function accepting zero or more int arguments
2
for _, n := range numbers
The variadic parameter is a slice inside the function, so range works on it
3
greet("Hello", "Alice", "Bob")
Can pass any number of string arguments after the required first parameter
4
nums := []int{10, 20, 30}; sum(nums...)
The ... unpacks a slice into individual arguments for the variadic function