Why Is String Indexing Not Allowed in Rust?

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);