Go

Variadic Functions

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
`...T` in the last parameter slot accepts zero or more T values. Pass a slice by suffixing with `...` to spread it. Used everywhere from `fmt.Println` to custom builders.
Go
Raw
package main

import "fmt"

func sum(nums ...int) int {
    total := 0
    for _, n := range nums {
        total += n
    }
    return total
}

func greet(prefix string, names ...string) {
    for _, n := range names {
        fmt.Println(prefix, n)
    }
}

func main() {
    fmt.Println(sum())                       // 0
    fmt.Println(sum(1, 2, 3, 4, 5))          // 15

    // Spread a slice into variadic args
    nums := []int{10, 20, 30}
    fmt.Println(sum(nums...))                // 60

    greet("Hello,", "Alice", "Bob", "Cara")
    // Hello, Alice
    // Hello, Bob
    // Hello, Cara
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.