How to Unpack Array as Arguments in Go
Created
Modified
Using Variadic Functions
Variadic functions can be called with any number of trailing arguments. Here’s a function that will take an arbitrary number of ints as arguments. For example,
package main
import "fmt"
// Variadic Functions
func sum(args ...int) int {
total := 0
for _, v := range args {
total += v
}
return total
}
func main() {
a := []int{1, 2, 3}
t := sum(a...)
fmt.Println(t)
t = sum(2, 3, 4)
fmt.Println(t)
}
6 9
Using Reflection
If you really want to do this dynamically on a function of fixed number of arguments, you can use reflection:
package main
import (
"fmt"
"reflect"
)
func sum(a, b, c int) int {
return a + b + c
}
func main() {
a := []int{1, 2, 3}
var args []reflect.Value
for _, v := range a {
args = append(args, reflect.ValueOf(v))
}
fun := reflect.ValueOf(sum)
result := fun.Call(args)
sum := result[0].Interface().(int)
fmt.Println(sum)
}
6