We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Runes and String Encoding

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.

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.

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.

UTF-8 Text

Type text to see its code points and bytes. Joining adjacent emoji inserts a zero width joiner (U+200D).
6 code points· 9 bytes
bU+0062
0x62
oU+006F
0x6F
oU+006F
0x6F
tU+0074
0x74
sU+0073
0x73
🐻U+1F43B
0xF00x9F0x900xBB

One displayed symbol can contain multiple runes. Some emoji combine runes using a zero-width joiner (U+200D). The widget's 👨‍👩 contains three runes: two emoji and the joiner.

What Does This Mean?

There are 2 main takeaways:

  1. When you need to work with individual characters in a string, you should use the rune type. It breaks strings up into their individual characters, which can be more than one byte long.

  2. 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.

Assignment

Boots is a bear. (Not a dog, haters).

🐻

If you've got it right, you should notice that the emoji is only one rune, but it takes up 4 bytes.