Strings, bytes, and runes

A string is an immutable sequence of bytes. Length and "the number of letters" match only for ASCII.

A string in Go is immutable and stores bytes, almost always in UTF-8. len("Go") equals 2. len("Привет") equals 12, because each of these Cyrillic letters takes two bytes, while there are six letters. utf8.RuneCountInString counts code points.

Indexing s[0] returns a byte, type byte, not a letter. The loop for i, r := range s walks runes, and the index i is an offset in bytes, not the letter number. It jumps: 0, 1, 2 for ASCII and 0, 2, 4 for Cyrillic in UTF-8.

A slice of a string is also bytes: s[:2]. If you cut UTF-8 in the middle of a character, you get a broken string. For letters, first turn the string into []rune, cut that, and build it back with string(runes).

func Reverse(s string) string {
    r := []rune(s)
    for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
        r[i], r[j] = r[j], r[i]
    }
    return string(r)
}

Concatenation a + b creates a new string. In a loop over thousands of pieces that work is quadratic. strings.Builder belongs there. For taking text apart, look at the strings package: Fields, TrimSpace, Cut, Contains. Fields splits on any Unicode space and collapses repeats.

Immutability is good news for concurrency: a string can be handed between goroutines without a mutex. It is bad news for anyone who expects s[0] = 'A' to compile. It will not compile.

Where this shows up in review

Cutting "the first 140 characters" with s[:140] is safe only when you are sure the string is ASCII. For user text, take runes. The other way around: protocols, HTTP headers, and hashes are bytes. Do not run them through runes.

Practice

  1. String length

    What is len("Привет") equal to?

    • 6
    • 12
    • 7
    • 2
  2. Reversing a string

    Write Reverse(s string) string. The function reverses the string by code points, not by bytes. Reverse("абв") equals вба, Reverse("Go") equals oG, and an empty string stays empty.

  3. range over a string

    What is the index in the loop for i, r := range s, if s is a string?

    • The rune number, starting at 1
    • The offset in bytes
    • The byte number inside the current rune
    • The length of the remaining tail of the string