String::as_mut_str¶
Level: reference · for working programmers
One line: Borrows the String as a &mut str — mutable, but length-preserving, so only the ASCII in-place edits are available.
Stable since 1.7.0. Usable in a const context.
A &mut str can change bytes but not how many there are. That rules out pushing, inserting and removing, and leaves: make_ascii_uppercase, make_ascii_lowercase, split_at_mut, get_mut, and the unsafe byte access.
Anything that resizes has to be a String method instead.
As with as_str, deref coercion usually supplies this automatically — s.make_ascii_uppercase() on a String works without writing as_mut_str(). The explicit call is for the same three cases: generics, inference, and clarity.
Example¶
string_as_mut_str.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let mut s = String::from("hello world");
// Deref coercion supplies the &mut str here.
s.make_ascii_uppercase();
println!("{s:?}");
// The explicit form, and a sub-slice edit.
let mut t = String::from("hello world");
t.as_mut_str()[..5].make_ascii_uppercase();
println!("{t:?}");
// Two disjoint mutable halves.
let mut u = String::from("abcdef");
let (a, b) = u.as_mut_str().split_at_mut(3);
a.make_ascii_uppercase();
println!("{a:?} {b:?}");
// Length-preserving: growth needs a String method.
let mut v = String::from("abc");
let before = v.len();
v.as_mut_str().make_ascii_uppercase();
v.push('!');
println!("{before} -> {} (the push, not the edit)", v.len());
}
Verified output of string_as_mut_str.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::as_str— the shared versionstr::make_ascii_uppercase— the main thing a&mut stris forstr::split_at_mut— two mutable halvesString::as_mut_vec— the unsafe, resizable view
String::as_mut_str in the standard library ↗
Po polsku¶
&mut str pozwala zmieniać bajty, ale nie ich liczbę — i to jedno ograniczenie tłumaczy całą resztę strony: zostają make_ascii_uppercase, make_ascii_lowercase, split_at_mut i get_mut, a wszystko, co zmienia długość, musi być metodą String. Dla polskiego tekstu człon „ascii” w nazwie jest ostrzeżeniem, a nie ozdobnikiem: make_ascii_uppercase na "żółw" podniesie samo w, a ż, ó i ł zostawi nietknięte — prawdziwe wersaliki daje to_uppercase(), które zwraca nowy String, bo zmiana wielkości liter potrafi zmienić liczbę bajtów (niemieckie ß przechodzi w SS) i przez &mut str byłaby niewykonalna. Samego as_mut_str() zwykle nie trzeba pisać, bo dostarcza go automatyczna dereferencja; jawne wywołanie przydaje się przy typach generycznych, przy podpowiadaniu typu oraz wtedy, gdy edytujesz fragment — jak t.as_mut_str()[..5].make_ascii_uppercase(), po którym w przykładzie zostaje "HELLO world".
Szukaj po polsku: zmiana wielkości liter w miejscu · polskie znaki a wielkie litery · rust make_ascii_uppercase · rust &mut str length preserving