golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
123.36k stars 17.58k forks source link

proposal: spec: Allow interfaces to be inferrable generic types #69822

Open glossd opened 2 hours ago

glossd commented 2 hours ago

Go Programming Experience

Experienced

Other Languages Experience

Java, JS

Related Idea

Has this idea, or one like it, been proposed before?

It's been asked on Reddit once.

Does this affect error handling?

No

Is this about generics?

Yes

Proposal

I don't understand why type interface isn't automatically inferred. This is a literal example of the error code CannotInferTypeArgs

func f[T any]() {}
func _() {
    f() /* ERROR "cannot infer T" */
}

To understand the problem I decided to play around with the Go compiler and, surprisingly, made it work. I sent the changes for review For this demonstration, I limited the number of TypeParam to only 1 for a possible infer, because I can see how it can complicate things in cases such as f[T any, S [T]](){}. I also limited the interface type to a basic one If you consider having interfaces as inferrable generics, I'll be happy to contribute. First improvement is to allow multiple generic parameters to be inferred. My idea is to only infer the generic type if it's not used in any other generic parameters. Then it would sound good. I'd be happy to hear any feedback. Thank you for your time.

Language Spec Changes

The Go compiler would allow the type interface to be inferred.

Informal Change

This code compiles

func f[T []any]() {}
func _() {
    f()
}

This one doesn't

func f[T any]() {}
func _() {
    f()
}

It'd be great to infer T as any

Is this change backward compatible?

Yes, because now you'd have to specify the interface for code to compile.

Orthogonality: How does this change interact or overlap with existing features?

It expands the types for inferrable generics.

Would this change make Go easier or harder to learn, and why?

Yes. Not specifying generics when you don't need to is an improvement

Cost Description

I assume only an if block in the infer function.

Changes to Go ToolChain

src/cmd/compiler

Performance Costs

As far as I see now, the final solution would have O(n) for generic parameters, which are in 99% of cases less than 3

Prototype

https://go-review.googlesource.com/c/go/+/618855

gabyhelp commented 2 hours ago

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)