UTF-8 inside a String
Let's look closer at the lockers of a String: each one holds a single byte. A Latin letter fits into one locker, while a Cyrillic letter takes two neighboring ones. Some characters, such as many emoji, take four.
Because of this, strings sometimes surprise you. Compare two three-letter words:
fn main() {
let en = String::from("cat");
let ru = String::from("кот");
println!("{} {}", en.len(), ru.len()); // 3 6
}Both words have three letters, yet the lengths differ: 3 and 6. Let's find out what exactly len() counts.
UTF-8 bytes
To store letters of any alphabet, a String writes its text in the UTF-8 encoding: each character takes from one to four bytes. How many depends on the character:
- Latin letters, digits, the space and signs like
!take 1 byte; - Cyrillic letters take 2 bytes;
- many emoji take 4 bytes.
The len() method returns the number of bytes, not letters: the word "кот" has three letters of two bytes each, hence 6. To count characters, you take chars(): it walks the string and yields chars one by one, and count() counts them. A character's len_utf8() method tells how many bytes it takes in UTF-8.
Step through the program and watch how many bytes each character takes and how they add up to len().
1fn main() {2 let s = String::from("пёс!");3 println!("{}", s.len());4 println!("{}", s.chars().count());5 for c in s.chars() {6 println!("{c} {}", c.len_utf8());7 }8}
The string holds four characters: three Cyrillic letters and the sign "!".
A char itself always takes 4 bytes in memory: that way any character fits into it. But inside a string the characters are stored compactly, in UTF-8, so "пёс" is 6 bytes, not 12.
Here the locker analogy falls short: you can open any locker, but Rust lets you slice a string only at character boundaries. You can't take half a letter.
Why there is no s[0]
In Python and JavaScript you get a string's first letter as s[0]. In Rust you can't:
fn main() {
let s = String::from("пёс");
let c = s[0]; // ✗
println!("{c}");
}error[E0277]: the type `str` cannot be indexed by `{integer}`The program does not compile. The message says str: that is the name of the text itself inside a String. And {integer} means "some integer": the compiler has not yet chosen the exact type of the index 0.
It is unclear what s[0] should return: the first byte, which is half of the letter "п", or the first letter. And to find the letter number n, the string would have to be walked from the start, since letters differ in length. So Rust asks you to say explicitly what you need:
s.chars().next()is the first character wrapped in anOption: for "пёс" it isSome('п'), and for an empty string it isNone;s.as_bytes()[0]is the first byte, a number: for "пёс" it is208;s.bytes()yields all the bytes one by one, aschars()does for characters.
Interviewers like to ask this: "Why does a Rust string have no s[0] index?"
Common mistake
A string slice is taken by letter numbers, forgetting that the numbers in a slice count bytes:
fn main() {
let s = String::from("пёс");
println!("{}", &s[0..1]); // ✗
}end byte index 1 is not a char boundary; it is inside 'п' (bytes 0..2 of string)The program builds but stops with a panic when it runs. The slice 0..1 ends after byte 0, while the letter "п" takes bytes 0 and 1, which is what the message says. The first letter is the slice &s[0..2], and it is safer to get it with chars().
Key points
Stringstores UTF-8:len()counts bytes, and a Cyrillic letter takes two.chars().count()counts characters,chars().next()gives the first one,as_bytes()andbytes()give bytes.s[0]does not compile (E0277), and a slice in the middle of a letter is a panic.