Home > other >  GoLang cannot use (func() literal) (value of type func()) as func() []int value in argument to xxx
GoLang cannot use (func() literal) (value of type func()) as func() []int value in argument to xxx

Time:06-22

I'm learning generics in golang and I want to use generics to infer the return type of a function, but I get an error, what should I do?

package main

type A struct{}

func getList[T comparable](cb func() []T) []T {
    return cb()
}

func main() {
    // cannot use (func() literal) (value of type func()) as func() []int value in argument to getList[int]
    getList[int](func() { return []int{1, 2} })

    // cannot use (func() literal) (value of type func()) as func() []string value in argument to getList[string]
    getList[string](func() { return []string{"a", "b"} })

    // cannot use (func() literal) (value of type func()) as func() []A value in argument to getList[A]
    getList[A](func() { return []A{} })
}

How can I fix these errors

CodePudding user response:

The function literals are missing the return type. Add the return types as indicated here:

                    ↓↓↓↓↓
getList[int](func() []int { return []int{1, 2} })
  •  Tags:  
  • go
  • Related