Reputation: 15197
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.
Upvotes: 0
Views: 115
Reputation: 711
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\n", sum(1, 2, 3)) // passing multiple arguments
fmt.Printf("Sum: %v\n", sum(many...)) // arguments wrapped in a slice
}
Upvotes: 2
Reputation: 99234
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)})
Upvotes: 0