Home > Backend Development > Golang > How Do Variadic Functions in Go Handle an Arbitrary Number of Arguments?

How Do Variadic Functions in Go Handle an Arbitrary Number of Arguments?

Patricia Arquette
Release: 2024-12-01 10:24:15
Original
385 people have browsed it

How Do Variadic Functions in Go Handle an Arbitrary Number of Arguments?

Variadic Functions in Go

Golang offers a unique feature called variadic functions, which allows you to define functions that accept an arbitrary number of arguments. This provides a flexible way to handle functions with varying inputs.

In your example, you wish to define a function Add that takes any number of integers and returns their sum. In Go, you can achieve this using the syntax ...int, where the ellipsis (...) indicates the variable number of arguments. Here's a corrected version of your example:

package main

import "fmt"

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

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

As the spec mentions:

Given the function and call

func Greeting(prefix string, who ...string)
Greeting("hello:", "Joe", "Anna", "Eileen")
Copy after login

within Greeting, who will have the value []string{"Joe", "Anna", "Eileen"}

Therefore, when calling Add(1, 3, 4, 5), the num1 parameter will be a slice of integers containing the values [1, 3, 4, 5]. This slice can then be iterated to calculate the sum of the input numbers.

The above is the detailed content of How Do Variadic Functions in Go Handle an Arbitrary 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