str::split_at_mut_checked¶
Level: reference · for working programmers
One line: split_at_mut returning Option — None rather than a panic for a bad offset.
Stable since 1.80.0. Usable in a const context.
The mutable member of the checked pair. Same two refusals as split_at_checked — past the end, or inside a character — collapsed into one None.
Because the input is a &mut str and the output borrows it, a None gives the borrow back: you can ask, be refused, and still use the string afterwards.
Example¶
str_split_at_mut_checked.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut owned = String::from("héllo");
for mid in [1, 2, 3, 99] {
// The borrow is released again on None, so the loop can keep asking.
match owned.as_mut_str().split_at_mut_checked(mid) {
Some((a, b)) => println!("{mid:>2} -> {a:?} {b:?}"),
None => println!("{mid:>2} -> refused"),
}
}
// Edit one half in place once a legal offset is found.
if let Some((left, _)) = owned.as_mut_str().split_at_mut_checked(3) {
left.make_ascii_uppercase();
}
println!("{owned}");
}
Verified output of str_split_at_mut_checked.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::split_at_mut— the panicking versionstr::split_at_checked— the shared-reference versionstr::get_mut— the same idea for an arbitrary range
str::split_at_mut_checked in the standard library ↗
Po polsku¶
Mutowalna połowa pary „checked”: te same dwie odmowy co w split_at_checked — offset poza końcem albo w środku znaku — sklejone w jedno None, z tą różnicą, że na wejściu jest &mut str. To drugie ma konsekwencję, którą widać w pętli z przykładu: None nie niesie ze sobą żadnej referencji, więc pożyczenie (borrow) kończy się od razu i po odmowie (2 -> refused) można pytać dalej, a na końcu nadal korzystać z tekstu. Gdyby wariant odmowy zwracał referencję mutowalną, byłby to klasyczny przypadek warunkowo zwracanego pożyczenia, na którym borrow checker odrzuca kod wyglądający zupełnie sensownie — stąd wzorzec wart zapamiętania: najpierw pytaj przez split_at_mut_checked, a edytuj w miejscu (make_ascii_uppercase) dopiero po trafieniu w legalny offset.
Szukaj po polsku: warunkowe pożyczenie mutowalne · cięcie tekstu bez paniki · rust split_at_mut_checked · rust conditional mutable borrow NLL