What cast / assertion need I do in Go in order to pass to a function expecting a generic function like func(interface{}) interface{}
, a more specific function like func(int) int
instead?
For example, in code like this, fooA
can be passed to MakeExclamer
, but not fooB
:
func MakeExclamer(foo func (interface{}) interface{}, n int) func () {
return func() {
fmt.Printf("%v!!!", foo(n))
}
}
func fooA(x interface{}) interface{} {
return x.(int)*2
}
func fooB(x int) int {
return x * 10
}
func main() {
exclamerA := MakeExclamer(fooA, 12)
exclamerA()
exclamerB := MakeExclamer(fooB, 66)
// >> cannot use fooB (type func(int) int) as type func(interface {}) interface {} in argument to MakeExclamer
exclamerB()
}
(Go Playground link: https://play.golang.org/p/xGzfco0IAG)
I'm not interested much in alternative code structure patterns, since this is how I want it to work: a specific function should be passed to a general function transformer (accepting function of type Any -> Any
) that will return another general function (Any -> Any
). This may not be idiomatic in Go, but it is the pattern that I want my code to follow.