Go🔧Core Languagebeginner
Variadic Functions
Go · Core Language · Run with go run
Explanation
A variadic function accepts a variable number of trailing arguments of the same type, declared with `...T`. Inside the function the parameter is a slice `[]T`. An existing slice can be passed to a variadic parameter with the spread operator `slice...`.
Real-World Scenario
`fmt.Printf` and `append` are variadic. A custom `logf(format string, args ...any)` wrapper forwards its variadic args straight into `fmt.Sprintf(format, args...)` — adding a timestamp or prefix without changing the call signature users expect.
Quick Snippet
snippet.go
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
sum(1, 2, 3) // 6 — pass individual args
sum() // 0 — zero args is valid
nums := []int{4, 5, 6}
sum(nums...) // 15 — spread an existing sliceFull Example
variadic.go
// Compile: go run variadic.go
// Output:
// sum(1,2,3) = 6
// sum() = 0
// sum(nums...) = 15
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println("sum(1,2,3) =", sum(1, 2, 3))
fmt.Println("sum() =", sum())
nums := []int{4, 5, 6}
fmt.Println("sum(nums...) =", sum(nums...)) // spread a slice
}
Run command
go run variadic.go