Strings and Runes

You have used strings since your first program. Now it is time to look inside one. In Go, a string is a row of bytes. A byte is a small number from 0 to 255, and the computer uses these numbers to store the text.

package main

import "fmt"

func main() {
	word := "Go"
	name := "Zoë"
	fmt.Println(len(word), len(name))
}

Output:

2 4

Zoë has three characters, but len says 4. That is because len counts bytes, not characters. Go stores text in a format called UTF-8. In UTF-8, the English letters, digits and common symbols take one byte each. Other characters take more: ë takes two bytes, and a Chinese character like 東 takes three.

Indexing gives a byte

name[0] gives the byte at index 0. A byte prints as a number. To see it as text, convert it with string():

name := "Zoë"
fmt.Println(name[0], string(name[0]))

Output:

90 Z

90 is the number UTF-8 uses for Z. This works for Z because it is one byte. But ë is two bytes, at index 2 and index 3, and neither byte is a character on its own:

fmt.Println(name[2], name[3])
fmt.Println(string(name[3]))

Output:

195 171
«

string(name[3]) printed a different character, «. The byte is half of ë, and its value is 171. string() read 171 as a character code, and 171 is the code of «. So indexing is safe only for text where every character is one byte.

Runes

Go calls one character a rune. A character written in single quotes, like 'A', is a rune. Like a byte, a rune is stored as a number, its character code, and string() turns it back into text:

letter := 'ë'
fmt.Println(letter, string(letter))

Output:

235 ë

235 is the character code of ë. When you want to print a rune as a character, always convert it with string().

Range over a string

When you range over a string, Go reads it one rune at a time. Each pass gives you the byte index where the rune starts, and the rune:

for i, r := range "Zoë!" {
	fmt.Println(i, string(r))
}

Output:

0 Z
1 o
2 ë
4 !

Look at the indexes: 0, 1, 2 and then 4. The ë starts at index 2 and uses two bytes, so the next rune starts at index 4. The loop never cuts a character in half.

Converting to a slice of runes

When you need to count characters or reach one by its position, convert the string to a []rune. Each item is then one whole character:

runes := []rune("Zoë")
fmt.Println(len(runes))
fmt.Println(string(runes[2]))
fmt.Println(string(runes))

Output:

3
ë
Zoë

len(runes) is 3, the real number of characters, and runes[2] is the whole ë. string(runes) turns the slice back into a string.

So here is the rule. For text that has only English letters and digits, bytes and characters are the same, and indexing is fine. For a name typed by a person, use range or []rune, because you do not know which letters it has.

In the exercise, convert two names to runes, then print their initials and the number of characters in each name.