liveBook · Manning

Escape sequence

As explained in Learn Rust in a Month of Lunches

An escape sequence is a character sequence in a string literal that represents a special character or encoding instruction.

An escape sequence is a character sequence inside a string literal that represents something special. In Rust, \n starts a new line, \t inserts a tab, and \\ prints a backslash. section 2.10

Use escape sequences when string content would otherwise be difficult to write:

  • Escape quotation marks with \" and backslashes with \\. section 2.10
  • Write Unicode characters with \u{hexadecimal number}, such as \u{D589}. section 2.10
  • Use a raw string such as r#"..."# when many escapes make the text hard to read; add more # marks when the content contains a matching delimiter. section 2.10

Printing visible escape characters

println!("Here are two escape characters: \\n and \\t"); prints the characters \n and \t instead of creating a new line or tab. section 2.10

fn main() {
    println!("He said, \"You can find the file at
    c:\\files\\my_documents\\file.txt.\" Then I found the file.");   #1
    println!(r#"He said, "You can find the file at c:\files\my_documents\file.txt." Then I found the file."#);       #2
}
#1 We had to use \ eight times here—kind of annoying.
#2 Much better!

Compare an escaped string with a raw string containing quotes, backslashes, and a Windows-style path. section 2.10

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains common escapes, Unicode notation, raw-string alternatives, and delimiter adjustments, while stopping short of broader string formatting.
Examples
Shows newlines, tabs, escaped quotes, file paths, raw strings, hashtags, byte strings, and Unicode escapes.
What it assumes
Assumes familiarity with printing and string literals while explaining escape notation through minimal examples.
What you can do after
Apply it via Rust string literals to represent special characters and choose raw strings when escaping becomes cumbersome.
How it connects
Connects escape sequences with string literals, raw strings, Unicode, ASCII, and string printing.

Also explained in

Compare how 6 books explain escape sequence →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.