str::slice_mut_unchecked¶
Level: reference · for working programmers
Deprecated — use
str::get_unchecked_mutinstead. The page is here because the name is still in older code, and it still compiles; a new call site should not use it.
One line: The 1.0-era spelling of get_unchecked_mut, taking two usize arguments.
Stable since 1.5.0. unsafe — the caller carries the invariant described below.
s.slice_mut_unchecked(a, b) is s.get_unchecked_mut(a..b). Deprecated in 1.29 alongside its shared-reference twin.
Same contract: both offsets in range, both on character boundaries, and the result is a &mut str that cannot change length.
Example¶
str_slice_mut_unchecked.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
#![allow(deprecated)]
fn main() {
let mut owned = String::from("hello world");
unsafe { owned.as_mut_str().slice_mut_unchecked(0, 5) }.make_ascii_uppercase();
println!("{owned:?}");
let mut same = String::from("hello world");
unsafe { same.as_mut_str().get_unchecked_mut(0..5) }.make_ascii_uppercase();
println!("{same:?}");
println!("identical: {}", owned == same);
}
Verified output of str_slice_mut_unchecked.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::get_unchecked_mut— the method to usestr::get_mut— the safe versionstr::slice_unchecked— the other deprecated name
str::slice_mut_unchecked in the standard library ↗
Po polsku¶
To mutowalny bliźniak slice_unchecked — również wycofany (deprecated) w Ruście 1.29 na rzecz get_unchecked_mut(a..b) — ale ma jedno ograniczenie własne, o którym łatwo zapomnieć: zwrócony &mut str nie może zmienić długości. Wolno przez niego pisać tylko w miejsce, bajt za bajt, i dlatego jedyne, co się tu realnie robi, to metody z rodziny ascii, jak make_ascii_uppercase. Dla polskiego tekstu to od razu widać jako pułapka: make_ascii_uppercase przerobi a na A, ale ż zostawi nietknięte, bo dotyka wyłącznie zakresu ASCII — na „żółw” zadziała dokładnie w zerowym stopniu. Do zmiany wielkości polskich liter potrzebne jest to_uppercase, które zwraca nowy String, a nie zapisuje w istniejący wycinek; a ponieważ wersja unchecked niczego nie sprawdza, błędne przesunięcie w bajtach nie skończy się tu paniką, tylko zachowaniem niezdefiniowanym (undefined behaviour).
Szukaj po polsku: mutowalny wycinek łańcucha · zmiana wielkości polskich liter · metoda wycofana · rust get_unchecked_mut · rust make_ascii_uppercase non-ascii