str::escape_unicode¶
Level: reference · for working programmers
One line: Escapes every character as \u{...}, including plain ASCII letters — "ab" becomes \u{61}\u{62}.
Stable since 1.34.0.
No exceptions and no readability: a becomes \u{61}. That total uniformity is the point — the output has one shape per character, so it is trivial to parse back and impossible for any byte of the original to be interpreted as syntax.
Use it when the encoding is the subject: showing a reader exactly which code points a string contains, or comparing two strings that look identical on screen. Two spellings of é are indistinguishable visually and obvious here.
For logging or code generation, escape_default gives you ASCII output that a person can still read.
Example¶
str_escape_unicode.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.
fn main() {
println!("{}", "ab".escape_unicode());
println!("{}", "é".escape_unicode());
// The three escapes side by side.
let s = "a\né";
println!("debug {}", s.escape_debug());
println!("default {}", s.escape_default());
println!("unicode {}", s.escape_unicode());
// Where it earns its keep: two strings that look identical.
let precomposed = "é";
let combining = "e\u{301}";
println!("{precomposed} vs {combining} -- equal? {}", precomposed == combining);
println!("{}", precomposed.escape_unicode());
println!("{}", combining.escape_unicode());
}
Verified output of str_escape_unicode.rs — regenerated by tools/run_examples.py, never hand-typed.
\u{61}\u{62}
\u{e9}
debug a\né
default a\n\u{e9}
unicode \u{61}\u{a}\u{e9}
é vs é -- equal? false
\u{e9}
\u{65}\u{301}
See also¶
str::escape_debug— the readable versionstr::escape_default— ASCII-safe but still readablestr::chars— the code points themselves
str::escape_unicode in the standard library ↗
Po polsku¶
Tutaj nie ma ani wyjątków, ani czytelności: każdy znak, łącznie ze zwykłym a, wychodzi jako \u{…}. Ta całkowita jednolitość jest właśnie zaletą — wyjście ma jeden kształt na znak, więc łatwo je sparsować z powrotem i żaden bajt oryginału nie zostanie wzięty za składnię. Po escape_unicode sięga się wtedy, gdy tematem jest samo kodowanie, i dla polskiego tekstu jest to narzędzie diagnostyczne pierwszego wyboru: "ó" bywa jednym znakiem \u{f3}, a bywa dwoma — \u{6f}\u{301}, czyli o plus łączący akut — przy czym na ekranie wyglądają identycznie, a == zwraca false, dokładnie jak é w przykładzie powyżej. Tak potrafią wyglądać nazwy plików przeniesione z macOS-a albo teksty sklejone z dwóch źródeł; różnicę widać tu natychmiast, a do sensownego porównywania takich łańcuchów potrzebna jest normalizacja Unicode, której biblioteka standardowa nie ma — daje ją crate unicode-normalization.
Szukaj po polsku: normalizacja Unicode · znaki łączące · rust escape_unicode · rust unicode-normalization NFC