str::make_ascii_uppercase¶
Level: reference · for working programmers
One line: Uppercases a–z in place, allocating nothing — the mirror of make_ascii_lowercase.
Stable since 1.23.0. Usable in a const context.
Same shape, same reason it is ASCII-only: ß → SS would need the string to grow, and a &mut str cannot.
ß is therefore left alone here, quietly — which is the right behaviour for an ASCII operation and the wrong result if you thought you were uppercasing German.
Returns (). Works on a sub-slice, which is how you uppercase one field of a buffer without touching the rest.
Example¶
str_make_ascii_uppercase.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 straße");
s.make_ascii_uppercase();
println!("{s:?}"); // ß untouched
// Compare with the allocating Unicode version.
println!("{:?}", "hello straße".to_uppercase());
// One field of a buffer, in place.
let mut record = String::from("name:alice");
if let Some(i) = record.find(':') {
record.as_mut_str()[i + 1..].make_ascii_uppercase();
}
println!("{record:?}");
// Title-casing the ASCII way: first byte only.
let mut word = String::from("rust");
word.as_mut_str()[..1].make_ascii_uppercase();
println!("{word:?}");
}
Verified output of str_make_ascii_uppercase.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
str::make_ascii_lowercase— the other directionstr::to_ascii_uppercase— the allocating versionstr::split_at_mut— getting two mutable halves to edit separatelyString::as_mut_str— where the&mut strcomes from
str::make_ascii_uppercase in the standard library ↗
Po polsku¶
To lustrzane odbicie make_ascii_lowercase, z tym samym ograniczeniem i z tego samego powodu: ß → SS wydłużyłoby łańcuch, a &mut str długości zmienić nie może, więc ß zostaje po cichu nietknięte. Dla polskiego czytelnika najciekawszy jest ostatni przykład ze strony — „title case po ASCII-owemu", czyli word.as_mut_str()[..1].make_ascii_uppercase(). Na "rust" to działa, ale na "ładny" panikuje: ł zajmuje w UTF-8 dwa bajty, więc bajt numer 1 nie leży na granicy znaku (end byte index 1 is not a char boundary; it is inside 'ł' (bytes 0..2 of string)) — i dokładnie tak samo skończy się każde polskie słowo zaczynające się od ą ć ę ł ń ó ś ź ż. Że to panika, a nie cichy zły wynik, jest tu akurat dobrą wiadomością; do podniesienia pierwszej litery używaj iteratora znaków (chars()), a make_ascii_uppercase() zostaw danym, które są ASCII z definicji.
Szukaj po polsku: granica znaku UTF-8 · pierwsza litera wielka w Ruscie · indeksowanie łańcucha bajtami · rust char boundary panic · rust capitalize first letter