HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

Go Unpacking Array As Arguments

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arrayargumentsunpacking

Problem

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)
}

Solution

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

Code Snippets

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)
}

Context

Stack Overflow Q#17555857, score: 291

Revisions (0)

No revisions yet.