Index expressions
…
For
a
of slice typeS
:
- if
x
is out of range at run time, a run-time panic occursa[x]
is the slice element at indexx
and the type ofa[x]
is the element type ofS
This is essentially identical to the rules for arrays, except that there’s no possibility of a compile-time error when using a constant index, since the length of a slice is not known at compilation time.
For
a
of string type:
- a constant index must be in range if the string a is also constant
- if
x
is out of range at run time, a run-time panic occursa[x]
is the non-constant byte value at indexx
and the type ofa[x]
is bytea[x]
may not be assigned to
These last two points are particular for strings. Recall that strings are immutable in Go. That is, you cannot change them in place.
str := "some string"
str = "another string" // Creates an entirely new string, rather than modifying the original
These last two rules are there to preserve this property.
Let’s look at the first: When you take the index of a single byte in a string, you get a copy, so that the string remains unchanged if you mutate the returned byte.
str := "some string"
x := str[0]
fmt.Println(str, x) // some string 115
x = 'X' // The original string remains unchanged
fmt.Println(str, x) // some string 88
And the second: While you can mutate the result of the expression a[x]
, you cannot assign to a[x]
:
str := "some string"
str[0] = 'X' // cannot assign to str[0] (neither addressable nor a map index expression)
Quotes from The Go Programming Language Specification Version of August 2, 2023