Type parameter declarations

August 1, 2023

Type parameter declarations

A type parameter list declares the type parameters of a generic function or type declaration. The type parameter list looks like an ordinary function parameter list except that the type parameter names must all be present and the list is enclosed in square brackets rather than parentheses.

TypeParameters  = "[" TypeParamList [ "," ] "]" .
TypeParamList   = TypeParamDecl { "," TypeParamDecl } .
TypeParamDecl   = IdentifierList TypeConstraint .

All non-blank names in the list must be unique. Each name declares a type parameter, which is a new and different named type that acts as a place holder for an (as of yet) unknown type in the declaration. The type parameter is replaced with a type argument upon instantiation of the generic function or type.

[P any]
[S interface{ ~[]byte|string }]
[S ~[]E, E any]
[P Constraint[int]]
[_ any]

I don’t think anything here is very surprising. Perhaps most notable is that, in contrast to function parameter lists, you cannot omit the names in a parameter list.

type x func(any, any) // Valid: No names in parameter list

type y List1[T1 any, T2 any] // Valid: Named parameters

type z List2[any, any] // Invalid

type q List3[_ any, _ any] // Valid: You can still use blanks for names, though

Quotes from The Go Programming Language Specification Version of December 15, 2022

Share this