Safe string slicing
Quick answer
UTF-8 strings cannot be indexed by a single integer because a byte position is not necessarily a whole character. A range can borrow a substring only when both endpoints are valid UTF-8 boundaries and the range is in bounds.
Check the byte range
&text[start..end] panics for invalid UTF-8 boundaries or out-of-range indices. text.get(start..end) instead returns an Option: Some contains a valid view and None means the range is invalid. The next chapter explains Option in depth; is_some() checks whether it contains a value. To find scalar positions, char_indices() yields byte offsets and chars.
fn main() { let text = "سلام"; println!("{:?}", text.get(0..2)); println!("valid: {}", text.get(0..1).is_some());}Expected stdout (not executed):
Some("س")valid: falseThe first letter needs two bytes; a one-byte prefix would split its encoding.
fn main() { for (offset, c) in "Aé".char_indices() { println!("{offset}: {c}"); }}Expected stdout (not executed):
0: A1: éThe offsets are byte positions, not grapheme indices.
Common mistake
Do not slice arbitrary UTF-8 using a character count as a byte offset.
Try it yourself
Use get to test the ranges 0..2, 2..4 and 1..3 on "سلام"; explain each result.
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
Safe string slicing — practice quiz
Choose one answer per question, then review the explanation.
What does `"بa".get(0..2)` return?
What does char_indices yield?
What is the result of `"abc".get(1..9)`?