In JavaScript, you can use .apply
to call a function and pass in an array/slice to use as function arguments.
function SomeFunc(one, two, three) {}
SomeFunc.apply(this, [1,2,3])
I'm wondering if there's an equivalent in Go?
func SomeFunc(one, two, three int) {}
SomeFunc.apply([]int{1, 2, 3})
The Go example is just to give you an idea.
They are called variadic functions and use the ...
syntax, see Passing arguments to ... parameters in the language specification.
An example of it:
package main
import "fmt"
func sum(nums ...int) (total int) {
for _, n := range nums { // don't care about the index
total += n
}
return
}
func main() {
many := []int{1,2,3,4,5,6,7}
fmt.Printf("Sum: %v
", sum(1, 2, 3)) // passing multiple arguments
fmt.Printf("Sum: %v
", sum(many...)) // arguments wrapped in a slice
}
It is possible using reflection, specifically Value.Call
, however you really should rethink why you want to do that, also look into interfaces.
fn := reflect.ValueOf(SomeFunc)
fn.Call([]reflect.Value{reflect.ValueOf(10), reflect.ValueOf(20), reflect.ValueOf(30)})