Home >Backend Development >Golang >How Can I Create a Go Function with a Variable Number of Arguments?

How Can I Create a Go Function with a Variable Number of Arguments?

Susan Sarandon
Susan SarandonOriginal
2024-12-01 11:28:121036browse

How Can I Create a Go Function with a Variable Number of Arguments?

Variadic Functions in Golang

Question:

Is there a way to define a Go function that accepts an arbitrary number of arguments?

Solution:

Yes, Go supports variadic functions, which allow you to pass a variable number of arguments to a function. To define a variadic function, use the ellipsis (...) syntax followed by the type of the arguments you want to accept.

For example, here is a variadic function named Add that can accept any number of int arguments:

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

You can call this function with any number of arguments, like this:

fmt.Println(Add(1, 3, 4, 5)) // Output: 13

Note:

In the example above, we used "..." (ellipsis) followed by "int" to indicate that the function accepts a variable number of int arguments. The variable named "num1" then represents a slice of integers, which contains all the arguments passed to the function.

The above is the detailed content of How Can I Create a Go Function with 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