Go by Example

Strings and Runes

Go strings are immutable byte sequences and may contain arbitrary bytes; a rune represents a Unicode code point.

A Go string is a read-only sequence of bytes. Text is often encoded as UTF-8, a format that stores text using one or more bytes for each symbol, but a string can hold any bytes. A rune is an int32 value used for one Unicode code point, a number assigned to a symbol by the Unicode text standard.

len counts bytes and indexing returns one byte. Ranging over a string decodes runes one at a time, with each index giving the byte position where that rune begins.

package main
 
import (
    "fmt"
    "unicode/utf8"
)
 
func main() {
    s := "café"
    fmt.Println(len(s))                    // 5 bytes
    fmt.Println(utf8.RuneCountInString(s)) // 4 code points
    fmt.Printf("%x\n", s[3])               // c3, first byte of é
 
    for i, r := range s {
        fmt.Printf("%d %c\n", i, r)
    }
}

In production

One displayed character may use several runes, as with some emoji and accented letters. Slicing a string by byte position can split its text encoding. For text editing or truncation that should follow what people see as one character, use a library that groups runes into displayed characters.

Enjoyed this? Get more software craft delivered to your inbox.