Circular generic types

July 27, 2023

There’s a lot to cover within type definitions! We’re several days in, and still going strong…

Type definitions

In a type definition the given type cannot be a type parameter.

type T[P any] P    // illegal: P is a type parameter

func f[T any]() {
	type L T   // illegal: T is a type parameter declared by the enclosing function
}

I expect this will surprise noone. We’ve already seen that struct, array, and slice types cannot reference themselves. This is just the logical application of the same idea to generic types.

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


Index expressions for type parameters

Index expressions … For a of type parameter type P: So just a reminder what this means: We’re talking about index expressions for different data types. And we’re going through different interpretations of the expression a[x]. In this example, a is of a “type parameter” type, represented by P. And as a further reminder, a type parameter looks something like [X any] or [Y ~int]. So for this example, we’re assuming that we have [P <.


Composite keys

This week’s episode of the Cup o’ Go podcast is out! Keep up with the Go community in just 15 minutes per week! Have a listen! Composite literals … The key is interpreted as a field name for struct literals, an index for array and slice literals, and a key for map literals. For map literals, all elements must have a key. If you’ve written any Go code, you probably already know about keys in maps:


Assignability of composite components

Composite literals … The types of the elements and keys must be [assignable(https://go.dev/ref/spec#Assignability)] to the respective field, element, and key types of type T; there is no additional conversion. This shouldn’t be surprising, but let’s examine the implications just the same. type myStr string s := myStr("my string") var x = map[int]string{ 3: "oink", // Valid, untyped numeric constant 3 is assignable to an int. int(4): "quack", // Valid, int(4) is of type int int64(12): "moo", // Invalid, int64(12) is not converted to int 8: s, // Invalid, type myStr is type string 9: string(s), // Valid; explicit conversion to type string } Quotes from The Go Programming Language Specification Version of August 2, 2023

Get daily content like this in your inbox!

Subscribe