Skip to content

spec: generics: permit type parameters on aliases #46477

Closed
@mdempsky

Description

The generics proposal says "A type alias may refer to a generic type, but the type alias may not have its own parameters. This restriction exists because it is unclear how to handle a type alias with type parameters that have constraints."

I propose this should be relaxed and type aliases allowed to have their own type parameters. I think there's a clear way to handle type aliases with constrained type parameters: uses of the type alias need to satisfy the constraints, and within the underlying type expression those parameters can be used to instantiate other generic types that they satisfy.

I think it's fine to continue allowing type VectorAlias = Vector as in the proposal, but this should be considered short-hand for type VectorAlias[T any] = Vector[T]. More generally, for generic type B with type parameters [T1 C1, T2 C2, ..., Tn Cn], then type A = B would be the same as type A[T1 C1, T2 C2, ..., Tn Cn] = B[T1, T2, ..., Tn].

In particular, something like this would be an error:

type A[T comparable] int
type B[U any] = A[U]   // ERROR: U does not satisfy comparable
type C B[int]

As justification for this, analogous code in the value domain would give an error:

func F(x int) {}
func G(y interface{}) { F(y) }  // ERROR: cannot use y (type interface{}) as int
func H() { G(42) }

I suspect if TParams is moved from Named to TypeName and type instantiation is similarly changed to start from the TypeName instead of the Type, then this should work okay.

/cc @griesemer @ianlancetaylor @findleyr @bcmills

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Type

No type

Projects

  • Status

    Accepted

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions