Rust Foundations · 10 min · free with an account

Characters & Text

Lesson preview · about 30%

Rust text has several useful units: bytes for encoding, Unicode scalar values for char, and sometimes multiple scalars for one visible symbol.

Core idea

String indexing by an arbitrary byte is forbidden because UTF-8 boundaries matter.

Start with the idea

Single quotes construct a char, while double quotes construct text. A char is one Unicode scalar value, not necessarily one byte. The crab emoji in the example fits in one char but occupies several UTF-8 bytes. &str is a borrowed view of UTF-8 text; its len() reports bytes. If you ask for chars().count(), you count scalar values instead. A user-perceived character can contain more than one scalar, such as a letter plus a combining mark, so even that count is not a universal measure of what a person sees.

Rust does not allow s[0] on a string because byte position zero is not a safe general-purpose character index. Instead, choose the operation that matches the question: bytes() when inspecting the encoding, chars() when processing scalars, and a grapheme-aware library when the interface needs visible clusters. This distinction prevents slicing through a multibyte UTF-8 sequence.

Keep learning, for free

The rest of this lesson is waiting for you.

Create a free account to read the complete explanation, see the infographic, explore the code, and try the exercises. All 742 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Basics