189. str::char_indices — Slice a String Without Panicking on Non-ASCII
chars().enumerate() hands you a character count, but &s[..] wants a byte offset. Mix them up and one accented letter blows your program apart.
Say you want everything from the underscore onward. The enumerate version looks right and works fine in tests full of ASCII:
| |
idx is 4, the character position. Byte 4 lands in the middle of é, so the slice panics: byte index 4 is not a char boundary.
char_indices yields the real byte offset of each character, which is exactly what slicing expects:
| |
The pattern is (byte_offset, char) instead of enumerate’s (count, char). It’s also a DoubleEndedIterator, so next_back gives you the last character and where it begins:
| |
Rule of thumb: the moment a character index touches &s[..], .split_at(), or any byte-indexed API, reach for char_indices — not enumerate.