Skip to content

proposal: spec: infer generic function type even when it's called #61712

Open
@rogpeppe

Description

@rogpeppe

As of current tip (fb6f38d), this code works:

package main

func main() {
	g(1, mkf)
}

func g[T any](x T, f func() func(T)) {}

func mkf[T any]() func(T) {
	return func(x T) {}
}

but this code fails, because cannot infer the type of mkf when it's been called:

package main

func main() {
	g(1, mkf())
}

func g[T any](x T, f func(T)) {}

func mkf[T any]() func(T) {
	return func(x T) {}
}

It's entirely possible that getting this to work might increase the complexity of the spec too much, but I'm raising this issue to track the possibility, because it's not an uncommon pattern. In particular, the functions used in the "functional options" pattern often return a closure that operates on the receiving type, but the lack of inference forces the caller to explicitly pass the type parameter in such cases. Here's a small example of that pattern: https://go.dev/play/p/kJJWceSqlNM?v=gotip

@griesemer

Metadata

Metadata

Assignees

No one assigned

    Labels

    NeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.ProposalTypeInferenceIssue is related to generic type inferencegenericsIssue is related to generics

    Type

    No type

    Projects

    Status

    Incoming

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions