将数组作为参数拆包 [英] Go Unpacking Array As Arguments
本文介绍了将数组作为参数拆包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有些人认为:
(
func main(){
arr: = [] int {2,4}
sum:= my_func(arr)
}
如果我犯了一个语法/各种错误,我会道歉。
解决方案
您可以使用类似于C的可变参数语法:
package main
importfmt
func my_func(args ... int)int {
sum := 0
for _,v:=范围参数{
sum = sum + v
}
返回金额;
func main(){
arr:= [] int {2,4}
sum:= my_func(arr ...)
fmt.Println(Sum is,sum)
}
尽可能多的东西,你想要的。在调用 my_func
函数后注意重要的 ...
。
运行示例: http://ideone.com/8htWfx
So in Python and Ruby there is the splat operator (*) for unpacking an array as arguments. In Javascript there is the .apply() function. Is there a way of unpacking an array/slice as function arguments in Go? Any resources for this would be great as well!
Something along the lines of this:
func my_func(a, b int) (int) {
return a + b
}
func main() {
arr := []int{2,4}
sum := my_func(arr)
}
I do apologize if I'm making an syntactical/assorted mistakes. I'm new to Go.
解决方案
You can use a vararg syntax similar to C:
package main
import "fmt"
func my_func( args ...int) int {
sum := 0
for _,v := range args {
sum = sum + v
}
return sum;
}
func main() {
arr := []int{2,4}
sum := my_func(arr...)
fmt.Println("Sum is ", sum)
}
Now you can sum as many things as you'd like. Notice the important ...
after when you call the my_func
function.
Running example: http://ideone.com/8htWfx
这篇关于将数组作为参数拆包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文