Search code examples
govariadic-functions

Can a custom function type be variadic?


I have this custom function type MyFuncType that accepts a single argument of type MyStruct:

type MyStruct struct {
  SomeVar string
}

type MyFuncType func(MyStruct)

var fn MyFuncType
fn = func(ms MyStruct) {//...}

Then I thought I could change the definition of MyFuncType to pass additional arguments:

type MyFuncType func(MyStruct, ...interface{})

var fn MyFuncType
fn = func(ms MyStruct, suffix string, anythigIWant int) {//...}

Now the compiler complains about incompatible type for fn. Ok, I think I can understand that a variable number of arguments can not define a function signature... But even with the definition below:

type MyFuncType func(MyStruct, interface{})

It's the same song. Finally it is not possible to use interface{} as [any]type for an argument in a custom function type or am I missing something here?

My workaround is to attach the implementation of functions of type MyFuncType to a struct which provides additional required data.


Solution

  • Your issue is the func signature, you need to define it exactly as it is in the type, and then you can use it sending whatever you want:

    type MyFuncType func(MyStruct, ...interface{})
    
    var fn MyFuncType
    fn = func(ms MyStruct, args...interface{}) {
        fmt.Println(ms.SomeVar, args[0], args[1])
    }
    
    // Using it as if the signature was:
    // func(ms MyStruct, suffix string, anythigIWant int)
    fn(MyStruct{SomeVar: "some var"}, "suffix", 123)
    

    Check it out: https://play.golang.org/p/R_qZoul9AcV