Scope of type parameters

June 27, 2023

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

  1. 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.

  1. 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


Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .

Related Content


Go 1.24.0 is here!

Go 1.24 is released! Yay! That means a short re-visit to the Go spec, as we look at things that have changed. From the release notes we see that there’s really only one significant change: Changes to the language¶ Go 1.24 now fully supports generic type aliases: a type alias may be parameterized like a defined type. See the language spec for details. For now, the feature can be disabled by setting GOEXPERIMENT=noaliastypeparams; but the aliastypeparams setting will be removed for Go 1.


unsafe.Slice

Package unsafe … The function Slice returns a slice whose underlying array starts at ptr and whose length and capacity are len. Slice(ptr, len) is equivalent to (*[len]ArbitraryType)(unsafe.Pointer(ptr))[:] except that, as a special case, if ptr is nil and len is zero, Slice returns nil [Go 1.17]. The len argument must be of integer type or an untyped constant. A constant len argument must be non-negative and representable by a value of type int; if it is an untyped constant it is given type int.


Allocation

Today’s topic: Allocation! What? You thought allocation was relegated to languages like C and C++? Yeah, that’s actually pretty close to true. We’re not learning about malloc today. Rather, we’re learning about the built-in function new, which gives us just one (of many!) ways to allocate memory for a variable. Allocation The built-in function new takes a type T, allocates storage for a variable of that type at run time, and returns a value of type *T pointing to it.

Get daily content like this in your inbox!

Subscribe