str::escape_default¶
Level: reference · for working programmers
One line: Escapes to pure ASCII — control characters, quotes, and every character above 127 become \u{...}.
Stable since 1.34.0.
Where escape_debug keeps é readable, this turns it into \u{e9}. The output is guaranteed ASCII, which is the property you want when writing to a channel that cannot be trusted with UTF-8: a log aggregator, a .properties file, a terminal of unknown encoding.
The escapes are Rust's own syntax, so the result is a valid Rust string literal body — which makes it the right tool for code generation.
It is lossless and mechanically reversible, but std has no unescaper; parsing it back is your problem or a crate's.
Example¶
str_escape_default.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
let s = "tab\there é 👋";
println!("{}", s.escape_default());
println!("{}", s.escape_debug());
// The output is always pure ASCII.
let escaped = s.escape_default().to_string();
println!("ascii: {}", escaped.is_ascii());
// Valid Rust literal syntax, which is what makes it usable for codegen.
println!("let s = \"{}\";", "a\"b\\c\né".escape_default());
// Every non-ASCII character becomes \u{...}.
println!("{}", "αβγ".escape_default());
}
Verified output of str_escape_default.rs — regenerated by tools/run_examples.py, never hand-typed.
tab\there \u{e9} \u{1f44b}
tab\there é 👋
ascii: true
let s = "a\"b\\c\n\u{e9}";
\u{3b1}\u{3b2}\u{3b3}
See also¶
str::escape_debug— keeps printable non-ASCII readablestr::escape_unicode— escapes ASCII toostr::is_ascii— the property the output guarantees- Printing bytes — the byte-slice version,
escape_ascii: ASCII kept, every other byte as\xNN
str::escape_default in the standard library ↗
Po polsku¶
Ta wersja gwarantuje jedno: wyjście jest czystym ASCII. Każda polska litera znika w kodzie — "żółw".escape_default() to \u{17c}\u{f3}\u{142}w — i dokładnie o to chodzi, gdy tekst trafia do kanału, któremu nie można ufać w sprawie UTF-8: agregatora logów, pliku .properties, terminala o nieznanym kodowaniu. Kto zna javowy native2ascii, ma tu dobrą intuicję, ale jedna rzecz się nie zgadza: to jest składnia Rusta, z klamrami i bez wiodących zer (\u{17c}), a nie javowa czy JSON-owa forma \u017C — więc tego wyjścia nie wkleisz wprost ani do .properties, ani do JSON-a. Zaletą tej samej składni jest to, że wynik stanowi poprawne wnętrze literału łańcuchowego w Ruscie — stąd naturalne zastosowanie w generowaniu kodu; drogi powrotnej biblioteka standardowa nie ma, odkodowanie trzeba napisać samemu albo wziąć z crate'a.
Szukaj po polsku: ucieczka do ASCII · polskie znaki w logach · rust escape_default · rust unescape string crate