Skip to the workspace
Pebellslearn by building
Data Types  ›  Capstone Project

Runes

Runes 15 minrune is an alias for int32, commonly used for a Unicode code point. A Go string stores bytes; decoding UTF-8 runes does not necessarily count user-perceived characters.

golang / Runes

Explore each scene at your own pace.

01 · The rule

The rule

Runes

rune is an alias for int32, commonly used for a Unicode code point. A Go string stores bytes; decoding UTF-8 runes does not necessarily count user-perceived characters.

Separate a Unicode code point from the bytes used to encode it.

tally reports the longest word in a text. On an English file it works; on a French menu it says café has 5 letters. Nothing is broken — Go is counting bytes, and é takes two of them. Runes are how Go talks about characters instead.

The rule

A rune is one character; a string is bytes; count characters as runes.

A rune is an alias for int32 and holds one Unicode code point. Rune literals use single quotes:

r := 'é'
fmt.Println(r)          // 233, the code point
fmt.Printf("%c\n", r)   // é
fmt.Println('A')        // 65

A string is a read-only sequence of bytes, normally UTF-8. In UTF-8, plain English letters take one byte, but é takes two, most other scripts take two or three, and emoji take four. So:

s := "café"
fmt.Println(len(s))                    // 5 (bytes)
fmt.Println(utf8.RuneCountInString(s)) // 4 (characters)
fmt.Println(len([]rune(s)))            // 4
fmt.Println(s[3])                      // 195, a byte, not a character

Indexing a string with s[i] gives a byte. To walk characters, use for range, which decodes UTF-8 for you:

for i, r := range "café" {
	fmt.Println(i, string(r))
}
// 0 c
// 1 a
// 2 f
// 3 é

i is the byte position where each character starts, and r is the rune. The unicode package works on runes: unicode.IsLetter(r), unicode.ToLower(r).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.