Home >Backend Development >Golang >Can Go Functions Accept a Variable Number of Arguments?

Can Go Functions Accept a Variable Number of Arguments?

Linda Hamilton
Linda HamiltonOriginal
2024-12-07 00:22:10913browse

Can Go Functions Accept a Variable Number of Arguments?

Does Go Support Functions with Variable Arguments?

In Go, you can create functions that can accept a variable number of arguments, known as variadic functions. This flexibility allows you to generalize functions to handle any number of inputs.

Example:

Consider the following code snippet where you aim to define a function Add that accepts an unknown number of integers:

func Add(num1... int) int {
    return args
}

func main() {
    fmt.Println("Hello, playground")
    fmt.Println(Add(1, 3, 4, 5))
}

In this code, the Add function is defined with ...int as the type of its final parameter. The syntax ... indicates that this parameter can accept multiple values of the specified type.

Solution:

As noted in the provided answer, the syntax for variadic parameters in Go is ...int, not just int. The revised code below demonstrates the correct usage:

func Add(num1... int) int {
    // Sum the numbers and return the result
    sum := 0
    for _, n := range num1 {
        sum += n
    }
    return sum
}

func main() {
    fmt.Println("Hello, playground")
    fmt.Println(Add(1, 3, 4, 5,))
}

With this modification, you can use the Add function with any number of integers as arguments, providing the flexibility you sought.

The above is the detailed content of Can Go Functions Accept a Variable Number of Arguments?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn