Index expressions for slices and strings

November 14, 2023

Index expressions

For a of slice type S:

  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the slice element at index x and the type of a[x] is the element type of S

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 occurs
  • a[x] is the non-constant byte value at index x and the type of a[x] is byte
  • a[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


Share this

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

Unsure? Browse the archive .