110. slice::split_at_checked — Split Without the Panic
slice.split_at(i) panics the second i > len. The usual fix is a length check wrapped around the call so you don’t blow up on a bad index. split_at_checked does the same job in one call and hands you an Option.
The classic trap — a single bad index away from a panic:
| |
The defensive version everyone writes:
| |
Two reads of i, one easy off-by-one (< vs <=), and a panic waiting if you ever drop the guard.
Rust 1.80 stabilised split_at_checked (and split_at_mut_checked), which folds the bounds check into the return type:
| |
Now the bounds check is the API. You get an Option<(&[T], &[T])> and the compiler nudges you to handle the None case:
| |
? does the bailout, no manual length check, no panic path. This works on &str too, where the index has to land on a UTF-8 boundary — and it returns None if it doesn’t, instead of panicking.