Skip to content

str::get_mut

str methods · Strings

Level: reference · for working programmers

One line: get returning Option<&mut str> — a checked mutable sub-slice.

pub const fn get_mut<I: SliceIndex<str>>(&mut self, i: I) -> Option<&mut I::Output>

Stable since 1.20.0. Usable in a const context.

Same two refusals as get, same None. What you can do with the result is the restricted set every &mut str allows: the ASCII in-place edits, and nothing that changes length.

The borrow lasts as long as the returned reference, so the usual pattern is to take it inside an if let and let it end at the closing brace.

Editing one field of a fixed-layout record in place is the realistic use — uppercase columns 4..8 of a buffer without copying the buffer.

Example

str_get_mut.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let mut owned = String::from("hello world");

    if let Some(part) = owned.get_mut(6..) {
        part.make_ascii_uppercase();
    }
    println!("{owned:?}");

    // Refused for the same two reasons as get.
    let mut accented = String::from("héllo");
    println!("{:?}", accented.get_mut(0..2).is_none());
    println!("{:?}", accented.get_mut(0..99).is_none());

    // A fixed-layout record: uppercase one column, in place.
    let mut record = String::from("id=42 name=alice");
    if let Some(name) = record.get_mut(11..) {
        name.make_ascii_uppercase();
    }
    println!("{record:?}");
}

Verified output of str_get_mut.rs — regenerated by tools/run_examples.py, never hand-typed.

"hello WORLD"
true
true
"id=42 name=ALICE"

See also

str::get_mut in the standard library ↗

Po polsku

get_mut odmawia dokładnie w tych samych dwóch przypadkach co get i zwraca Option<&mut str>, a to, co wolno z wynikiem zrobić, jest z rozmysłem wąskie: przeróbki ASCII w miejscu i nic, co zmienia długość — &mut str siedzi w cudzym buforze i nie ma jak go rozepchnąć. Stąd typowy zapis if let Some(part) = s.get_mut(6..): referencja mutowalna trzyma pożyczenie tak długo, jak sama żyje, więc wygodnie zamknąć je w bloku if let i pozwolić mu skończyć się na klamrze. Realne zastosowanie to rekord o stałym układzie — podnieść do wielkich liter kolumny 11.. bez kopiowania bufora — i tu jedno ostrzeżenie dla polskich danych: te „kolumny” liczone są w bajtach, więc jedno „ł” we wcześniejszym polu przesuwa cały układ o bajt i zakres, który wczoraj działał, dziś zwróci None albo trafi w nie to pole.

Szukaj po polsku: zasięg pożyczenia · edycja w miejscu · rekord o stałym układzie · rust str get_mut · rust &mut str ascii only