Golang支持可变参数函数吗?

huangapple go评论94阅读模式
英文:

Does Golang support variadic function?

问题

我想知道在Go语言中是否有一种方法可以定义一个接受未知数量变量的函数。

类似这样的写法:

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

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

我想将函数Add泛化,使其能够接受任意数量的输入。

英文:

I wonder if there a way where I can define a function for unknown number of variables in Go.

Something like this

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

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

I want to generalize the function Add for any number of inputs.

答案1

得分: 103

你基本上已经理解了,从我所看到的来看,但是语法是...int。请参考规范

给定函数和调用

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

在Greeting函数内部,who的值将是[]string{"Joe", "Anna", "Eileen"}

英文:

You've pretty much got it, from what I can tell, but the syntax is ...int. See the spec:

> Given the function and call
>
> func Greeting(prefix string, who ...string)
> Greeting("hello:", "Joe", "Anna", "Eileen")
>
> within Greeting, who will have the value []string{"Joe", "Anna", "Eileen"}

答案2

得分: 7

在使用可变参数时,你需要在函数内部使用循环来处理数据类型。

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

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

While using the variadic parameters, you need to use loop in the datatype inside your function.

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

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

答案3

得分: 3

Golang有一个非常简单的可变参数函数声明

可变参数函数可以接受任意数量的尾随参数。例如,fmt.Println是一个常见的可变参数函数。

下面是一个接受任意数量的int参数的函数示例。

package main

import (
    "fmt"
)

func sum(nums ...int) {
    fmt.Println(nums)
    for _, num := range nums {
        fmt.Print(num)
    }
}

func main() {
    sum(1, 2, 3, 4, 5, 6)
}

以上程序的输出结果为:

[1 2 3 4 5 6]

1 2 3 4 5 6

英文:

Golang have a very simple variadic function declaration

Variadic functions can be called with any number of trailing arguments. For example, fmt.Println is a common variadic function.

Here’s a function that will take an arbitrary number of int's as arguments.

package main

import (
    "fmt"
)

func sum(nums ...int) {
    fmt.Println(nums)
    for _, num := range nums {
        fmt.Print(num)
    }
}

func main() {
    sum(1, 2, 3, 4, 5, 6)
}

Output of the above program:

> [1 2 3 4 5 6]
>
> 1 2 3 4 5 6

huangapple
  • 本文由 发表于 2013年10月8日 10:33:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/19238143.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定