Runes in Go
Table of Contents
Go's rune type lets you work with Unicode code points that can take more than one byte in a UTF-8 string.
All the content from our Boot.dev courses are available for free here on the blog. This one is the "Constants and Formatting" chapter of Learn Go. If you want to try the far more immersive version of the course, do check it out!
Characters and Bytes
In many programming languages (cough, C, cough), a "character" is a single byte. Using ASCII encoding, the standard for the C programming language, we can represent 128 characters with 7 bits. This is enough for the English alphabet, numbers, and some special characters.
Runes
In Go, strings are just sequences of bytes: they can hold arbitrary data. However, Go also has a special type, rune, which is an alias for int32. This means that a rune is a 32-bit integer, which is large enough to hold any Unicode code point.
UTF-8 String Encoding
When you're working with strings, you need to be aware of the encoding (bytes -> representation). Go uses UTF-8 encoding, which is a variable-length encoding.
What Does This Mean?
There are 2 main takeaways:
- When you need to work with individual Unicode code points in a string, you should use the
runetype. It breaks strings up into code points, which can be more than one byte long. - We can include a wide variety of Unicode characters in our strings, such as emojis and Chinese characters, and Go will handle them just fine.
A Bear Emoji
The simple string boots has 5 bytes and 5 runes. The bear emoji is a different story:
package main
import (
"fmt"
"unicode/utf8"
)
func main() {
fmt.Println(len("boots")) // 5
fmt.Println(utf8.RuneCountInString("boots")) // 5
fmt.Println(len("🐻")) // 4
fmt.Println(utf8.RuneCountInString("🐻")) // 1
}
The emoji is only one rune, but it takes up 4 bytes.
Frequently Asked Questions
What is a rune in Go?
A rune is an alias for int32. It is a 32-bit integer, which is large enough to hold any Unicode code point.
Are Go strings sequences of bytes?
Yes. Go strings are sequences of bytes and can hold arbitrary data.
What string encoding does Go use?
Go uses UTF-8, which is a variable-length encoding.
When should you use runes in Go?
Use runes when you need to work with individual Unicode code points in a string because those code points can be more than one byte long.
How many bytes does the bear emoji use in Go?
The bear emoji is one rune, but it takes up four bytes.
