RUST / CHAPTER 04

UTF-8 strings and safe boundaries

Intermediate

Use bytes or characters deliberately without invalid string slicing.

By the end of this chapter

  • Distinguish byte length from char count
  • Use get for checked string slices
  • State limits of code-point processing

The idea

Rust String owns UTF-8 text, while &str borrows a valid text slice. The len method measures bytes, and chars iterates Unicode scalar values. These measurements can differ for accented letters and other non-ASCII text. A scalar value is still not always a complete displayed character, because combining marks can contribute to one visible unit. Choose the measurement required by your problem.

String slicing uses byte offsets and requires both endpoints to be valid UTF-8 boundaries. Direct indexing with an integer is unavailable because its meaning would be ambiguous. Use get with a range when invalid boundaries should produce None instead of a panic. For an ASCII-only format, validate that precondition before relying on one byte per character; do not generalize it to arbitrary user text.

Rust example
fn main(){ let s="café"; println!("{} {}",s.len(),s.chars().count()); println!("{}",s.get(0..3).unwrap()); println!("{}",s.get(3..4).is_none()); }
Result
5 4
caf
true

The final letter spans two bytes; a range ending inside it is rejected by get.

Try it yourself

Return the first Unicode scalar value as Option<char> without panicking on an empty string.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Why does "é".get(0..1) return None?