Function type with Variadic paramter


(Sandeep Bhat) #1

I need some help understanding how to do this.

package main

import (
"fmt"
)

func a(x, y int) {
fmt.Println("a")
}
func b(p, q, r int) {
fmt.Println("b")
}

type sample func(...interface{})

func d(i int, j sample) {
fmt.Println("d")
}

func main() {
d(2, a)
}

I see this is not allowed. Am I correct in the understanding that this is not ever allowed? Without variadic parameters it is a valid usage but not with variadic. Am I right?


(Jay Ts) #2

It appears the problem is that in main(), you are calling d() with an int (2) and a function (a). a() is defined as a function taking two integers. But d() is defined with a type sample as the second argument, with sample being a func(...interface{}), not int. They don’t match.

You can get it to compile and run if you define a() like this:

func a(...interface{}) {
        fmt.Println("a")
}

(Johan Dahl) #3

Yes as @jayts says above your type is a function with variable number of elements. And it is always this. It doesn’t match other functions with a fixed number of arguments. They are two different types.