Bytes and Unicode scalar values
Quick answer
Rust strings contain valid UTF-8. A single Unicode scalar value may occupy one to four bytes. Rust's char represents one scalar value, not necessarily one visible character.
Count the correct unit
text.len() returns the byte length. text.chars() provides a sequence of char values; count() counts them. as_bytes() gives a borrowed byte slice, useful for encoding-aware work. A sequence of scalars can form one grapheme cluster, so counting chars is not a universal count of user-perceived characters.
fn main() { let text = "سلام"; println!("bytes: {}", text.len()); println!("scalars: {}", text.chars().count());}Expected stdout (not executed):
bytes: 8scalars: 4Each of the four letters in this particular string occupies two UTF-8 bytes.
fn main() { let text = "Aé"; println!("{:?}", text.as_bytes()); for c in text.chars() { println!("{}", c); }}Expected stdout (not executed):
[65, 195, 169]AéA is one byte and é is two bytes in this composed form.
Common mistake
Do not use byte length as a universal text length shown to users.
Try it yourself
Compare "A", "é" and "🙂" using len and chars().count().
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bytes and Unicode scalar values — practice quiz
Choose one answer per question, then review the explanation.
For the UTF-8 string `"ب"`, what are len() and chars().count()?
What does `as_bytes()` provide on a string?
Can multiple char values form one user-perceived character?