If you missed it, we had a great Boldly Go: Live livestream yesterday. I built a basic linter from scratch. It was easier than I expected, and we all learned a few things. It’s not too late to catch the replay if you’re interested!
Type parameters are what power generics, and they have two specific scoping rules:
Declarations and scope
…
- The scope of an identifier denoting a type parameter of a function or declared by a method receiver begins after the name of the function and ends at the end of the function body.
func Index[T comparable](s []T, x T) int {
/* ... */
}
This differs from the scope of function parameters, in that the scope extends further–it’s not limited only to the function body, but also the function signature, including the list of type parameters.
- The scope of an identifier denoting a type parameter of a type begins after the name of the type and ends at the end of the TypeSpec.
type List[T any] struct {
next *List[T]
value T
}
So in this case, the scope of T
starts at [T any]
and ends at }
.
Quotes from The Go Programming Language Specification Version of December 15, 2022