R
RUSTY YELLOW PAGES

Escape sequencesLiteral


Explanation

Inside a (non-raw) string, character, or byte literal, a backslash introduces an escape sequence:

  • Quote escapes: \', \"
  • Common ASCII escapes: \n (newline), \r (carriage return), \t (tab), \\ (backslash), \0 (null)
  • Numeric byte escape: \xNN — two hex digits; in a char/str context restricted to \x00\x7F (7-bit — \x denotes a raw byte, and values ≥ 0x80 would be ambiguous between a byte and a code point, so Rust requires \u{...} there instead), but a full 8-bit \x00\xFF in a b'...'/b"..." byte context
  • Unicode escape: \u{7FFF} — up to six hex digits in braces, representing any Unicode scalar value; legal in char/str and c"..." contexts, but not in byte literals
  • Line-continuation escape: a backslash immediately followed by a newline strips the newline and any leading whitespace on the next line, letting a long string literal be wrapped across source lines without embedding the line break itself

None of these are processed inside a raw string/byte-string literal — see raw string literal.

Usage examples

Embedding escape sequences in a string

let s = "tab\tnewline\n";
//          ^^ ^^ escape sequences, processed at compile time

A \xNN byte escape inside a char/str context is limited to \x00\x7F (7-bit) — the full 8-bit range \x00\xFF is only legal inside a byte (b'...'/b"...") literal.

Working with text

Embedding \n/\t directly inside one string literal keeps a short multi-line template as a single readable value.

fn format_receipt(item: &str, qty: u32, price_cents: u32) -> String {
    format!("{item}\n  qty: {qty}\n  price: ${price_cents}\n") // <- `\n` escape sequences: line breaks in one literal
}

print!("{}", format_receipt("widget", 3, 499));

Embedding \n/\t inside one literal keeps the template readable as "the shape of the output" in one place, rather than splicing separate pieces together — the escapes are resolved once, at compile time, into the exact bytes the string holds.

Serializing and deserializing

Rust's compile-time escape rules and JSON's runtime string-escaping rules look similar but aren't identical — worth knowing before hand-building any JSON text.

// Rust's `\u{...}` escape (braced, variable-length hex) is *literal* syntax,
// resolved by rustc at compile time -- it is not the same thing as JSON's escape.
let heart: char = '\u{2764}'; // <- Rust escape sequence: braced hex, resolved when this file compiles

// JSON escapes the same code point as `❤` -- exactly four hex digits, no braces --
// and that escaping is *data*, checked by a JSON parser at runtime, not by rustc.
// The raw string below holds that JSON text verbatim; rustc never interprets the `❤`.
let json_fragment = r#"{"symbol": "❤"}"#; // <- `❤` here is JSON syntax, untouched by Rust

Rust's escape rules and JSON's string-escape rules differ in small but real ways (braced vs unbraced \u, no \x byte escape in JSON at all) — the practical consequence is to let a JSON library like serde_json own all JSON escaping rather than hand-building JSON text with Rust string literals.

Explanation

Embedded support: Full

Escape-sequence processing is pure lexical, compile-time work — it happens identically whether the target is hosted or #![no_std], with no runtime or allocator involved at any point. The escapes that come up most in embedded code are exactly the control-character ones: \r\n line endings (many serial terminals and AT-command interfaces expect CRLF, not a bare \n), \0 for a nul-terminated C string handed across FFI, and \xNN hex byte escapes for framing bytes or raw control codes — \x1B in particular is the ASCII ESC character that begins an ANSI/VT100 escape sequence, the standard way to color or position text on a serial terminal from firmware logging code.

Usage examples

Sending an ANSI color code over a serial terminal

fn log_error(uart: &mut impl core::fmt::Write, message: &str) {
    let _ = write!(uart, "\x1B[31m{message}\x1B[0m\r\n"); // <- `\x1B` escape: ANSI red-text, then reset, then CRLF line ending
}

Framing a boot banner for a terminal that expects CRLF

const READY_BANNER: &str = "boot ok\r\n"; // <- `\r\n` escape sequence: CRLF line ending a serial terminal expects