Index expressions for type parameters

November 16, 2023

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 <...>], with <...> being further clarified or limited below.

I don’t know if that helps in reading. It helps me understand what I’m writing at least. 😂

  • The index expression a[x] must be valid for values of all types in P’s type set.

So if we have a type parameter type [P []string | [4]string], then a[3] would be valid, because a[3] would be valid for both []string and [4]string types, but a["foo"] would not be valid.

  • The element types of all types in P’s type set must be identical. In this context, the element type of a string type is byte.

So [P []string | [4]string] is valid, because the element type of both types is string, but [P []string | []int] is not valid, because the element types (string and int) are not identical.

As a special case in this context, a string is treated essentially as a []byte, so [P string | []byte | [16]byte] is considered valid.

  • If there is a map type in the type set of P, all types in that type set must be map types, and the respective key types must be all identical.

In other words, you can’t mix-and-match maps and other types. [P map[string]string | []string] is invalid.

  • a[x] is the array, slice, or string element at index x, or the map element with key x of the type argument that P is instantiated with, and the type of a[x] is the type of the (identical) element types.

I think this part is pretty straight forward. Once the concrete type is determined for the type parameter, a[x] behaves exactly as you would expect.

  • a[x] may not be assigned to if P’s type set includes string types.

If any of the types in P’s type set is a string, then you cannot assign to a[x], for the same reasons discussed a couple of days ago, with regard to string immutability.

Quotes from The Go Programming Language Specification Version of August 2, 2023


Share this

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

Unsure? Browse the archive .

Get daily content like this in your inbox!

Subscribe