Home > database >  How to pass func with any return type as parameter into another function?
How to pass func with any return type as parameter into another function?

Time:12-28

func F(f func()interface{})interface{} {
    return f()
}

func one() int {
    return 1
}
type A struct {}
func two() A {
  return A{}
}
func main() {

    a := F(one)
    b := F(two)
}

The code above will fail with error

cannot use one (type func() int) as type func() interface {} in argument to F
cannot use two (type func() A) as type func() interface {} in argument to F

My question is how to pass a func with any possible output as a parameter?

CodePudding user response:

A value of type int can be assigned to an interface{} variable; a value of type func() int can not be assigned to a value of type func() interface{}. This is true with any version of Go.

Thought, what you are attempting to do can be achieved with Go 1.18, where you can easily type-parametrize the function with T any (btw any is an alias of interface{}):

func callf[T any](f func() T) T {
    return f()
}

func one() int {
    return 1
}

type A struct {}
func two() A {
  return A{}
}

func main() {
    a := callf(one)
    b := callf(two)

    fmt.Println(a) // 1
    fmt.Println(b) // {}
}

https://gotipplay.golang.org/p/zCB5VUhQpXE

  • Related