aof type parameter type
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
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 | string], then
a would be valid, because
a would be valid for both
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
[P string | string] is valid, because the element type of both types is
[P string | int] is not valid, because the element types (
int) are not identical.
As a special case in this context, a
string is treated essentially as a
[P string | byte | 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
xof the type argument that
Pis 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