aof slice type
xis out of range at run time, a run-time panic occurs
a[x]is the slice element at index
xand the type of
a[x]is the element type of
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.
aof string type:
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 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
str := "some string" str = 'X' // cannot assign to str (neither addressable nor a map index expression)
Quotes from The Go Programming Language Specification Version of August 2, 2023