Values, Text and Callbacks · 14 min · free with an account

UTF-8 and Editor Offsets

Lesson preview · about 30%

Text positions need a declared coordinate system before they can be exchanged or sliced.

Core idea

Validate the coordinate system, source revision and UTF-8 boundaries before slicing text.

Start with the idea

Rust str is valid UTF-8. len counts bytes, and chars iterates Unicode scalar values. Neither operation counts user-perceived grapheme clusters in general. A decomposed accent can consist of two scalar values while users perceive one letter. Emoji can occupy several UTF-8 bytes and two UTF-16 code units even before considering combined sequences.

String slicing uses byte offsets and requires valid UTF-8 boundaries. get returns None for an invalid range instead of panicking through indexing. char_indices supplies byte offsets at scalar boundaries; those positions are still not necessarily grapheme boundaries. The example uses a two-byte accented letter and checks both the valid whole-letter range and an invalid split.

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 754 lessons and algorithm steps are included.

No payment details. Your account opens the complete Academy.

← All lessons in Rust Interview Prep