Search code examples
gogenericsanonymous-function

Generic function, can't be defined in form of anonymous?


e.g:

func f[T any](t T) T {
    var result T
    return result
}

// this got error !
var fAnonymous = func[T any](t T) T {
    var result T
    return result
}

fAnonymous got error, it says:

Function literal cannot have type parameters

So, why golang don't permit a anonymous function to be generic?


Solution

  • A function literal cannot be generic because the function literal produces a function value, and the function value cannot be generic. Similarly, if you have a generic function, you cannot use it as a function value. For example

    func RegularFunction() {}
    func GenericFunction[T any]() {}
    
    func main() {
        // fine, since regular function can act as a value
        var f1 func() = RegularFunction
        // not valid, since a generic function is not a function value
        // Error: "cannot use generic function GenericFunction without instantiation"
        var f2 func() = GenericFunction
        // fine, since the generic function has been instantiated
        var f3 func() = GenericFunction[int]
    }
    

    To put it another way:

    //             vvvvvvvvvvvvv this is the type of normalFunc
    var normalFunc func(int) int = func(i int) int {
        return i + 1
    }
    
    //              vvvvvv what type would go here?
    var genericFunc        = func[T any](t T) T {
        var result T
        return result
    }
    

    The variable fAnonymous cannot be given any type here. Generic functions are not a type in the Go type system; they are just a syntactic tool for instantiating functions with type substitution.