Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

                    ↓↓↓↓↓
getList[int](func() []int { return []int{1, 2} })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading