×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Go Pointers

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Go Variadic Functions

Last Updated : July 21, 2025

In Go, a variadic function is a function that can accept a variable number of arguments of the same type. It is useful when you don't know in advance how many values will be passed to the function, such as summing numbers or formatting strings.

Define a Variadic Function

To define a variadic function, use an ellipsis (...) before the type of the last parameter.

func functionName(arg ...datatype) {
    // function body
}

Example: Sum of Numbers

The following example shows how to use variadic functions in Go, allowing a function to accept a variable number of arguments:

package main
import "fmt"

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

func main() {
    fmt.Println("Sum of 3, 5:", sum(3, 5))
    fmt.Println("Sum of 1, 2, 3, 4:", sum(1, 2, 3, 4))
}

When you run the above code, the output will be:

Sum of 3, 5: 8
Sum of 1, 2, 3, 4: 10

Passing a Slice to a Variadic Function

You can also pass a slice to a variadic function using the ... operator.

Example

The following example demonstrates how to pass a slice to a variadic function in Go using the ... syntax:

package main
import "fmt"

func display(names ...string) {
    for _, name := range names {
        fmt.Println("Hello", name)
    }
}

func main() {
    friends := []string{"Alice", "Bob", "Charlie"}
    display(friends...) // Passing slice to variadic function
}

When you run the above code, the output will be:

Hello Alice
Hello Bob
Hello Charlie

Explanation

  • In sum(), any number of int arguments can be passed.
  • In display(), a slice of strings is expanded into individual arguments using ....
  • Variadic parameters must be the last in the function signature.

Go Variadic Functions Exercise

Select the correct option to complete each statement about variadic functions in Go.

  1. What symbol is used to declare a variadic parameter?
  2. Can you pass a slice to a variadic function?
  3. Which of the following function signatures is correct?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.