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.
Either your function is varargs, in which you can use a slice with the
...
notation as Hunter McMillen shows, or your function has a fixed number of arguments and you can unpack them when writing your code.If you really want to do this dynamically on a function of fixed number of arguments, you can use reflection:
You can use a vararg syntax similar to C:
Now you can sum as many things as you'd like. Notice the important
...
after when you call themy_func
function.Running example: http://ideone.com/8htWfx
No, there's no direct support for this in the language. Python and Ruby, as well as Javascript you're mentioning; are all dynamic/scripting languages. Go is way more closer to, for example, C than to any dynamic language. The 'apply' functionality is handy for dynamic languages, but of little use for static languages like C or Go,