英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论