Rust prevents string indexing to ensure UTF-8 safety, requiring iteration or byte slicing instead.
Rust forbids string indexing because UTF-8 characters are not fixed-size, so a numeric index cannot reliably point to a character boundary. Use chars().nth() to access characters by count or get() to safely retrieve a byte slice.
let s = "hello";
let c = s.chars().nth(0).unwrap();
let slice = s.get(0..1);
Rust strings store text in UTF-8, where characters can take up different amounts of space. Indexing by number assumes every character is the same size, which would break for many languages. Instead, you must iterate through the text to find the character you want, ensuring you never cut a character in half.