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
Release: 2024-12-01 11:28:12
Original
972 people have browsed it

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
}
Copy after login

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template