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 an immutable sequence of bytes. Text is often UTF-8, but Go also permits arbitrary bytes. A rune is an alias for int32 that represents a Unicode code point.

len counts bytes and indexing returns one byte. Ranging over a string decodes runes, with each index giving that rune's byte offset.

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

Rune counts are not display-character counts. Combining marks and emoji sequences can contain several code points, and slicing can split a UTF-8 encoding. For user-facing truncation or cursor movement, use a Unicode grapheme segmentation library.

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