0

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.

1
  • Go is not a dynamic language and you shouldn't really need to do that kind of thing in Go. Commented Sep 14, 2014 at 8:27

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. I actually found out about this a few hours later, surprised I hadn't tried it before. It seems obvious when you know.
0

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

4 Comments

What do you suggest with Interfaces?
@daryl I meant you should think why you need to use this kind of dynamic calling and see if you can replace it with an interface.
@OneOfOne this is the wrong solution, think thrice before you ever import reflect and especially when suggesting others to do so. See AndrewN's answer for the correct thing to do.
@Wessie It's the right the solution for the question, it is the closest thing to function.apply in javascript, Andrew's solution would only work for one type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.