daryl
daryl

Reputation: 15197

Use Array as function call arguments

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

Answers (2)

AndrewN
AndrewN

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
}

Playground example

Upvotes: 2

OneOfOne
OneOfOne

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

playground

Upvotes: 0

Related Questions