Start learning free

LESSON 58 OF 414 · STRINGS I

Escaping Characters in Rust: Quotes, Backslashes and Newlines

Lesson Read the full explanation

There are times when we want to use quotes inside a string. For example, suppose we want to print the message I am John "the coder" Doe:

println!("I am John "the coder" Doe");

You can already see by the text color that we have a problem. Rust recognizes the string to be only I am John , and the rest of the line is not valid code, so the compiler reports an error.

Rust finds the first quotation mark and interprets that the string starts there. But then, it finds the second quotation mark (after John ) and interprets the string ends there.

Character escaping comes to our rescue!


Escaping characters:

In Rust, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, double quotes (") is considered a special character by Rust. Its job is to let Rust know when a string declaration starts / ends.

There is a way to print special characters like these in Rust, and that is by using the backslash character (\).

When we put \ before a special character, we tell Rust:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a double quote, Rust no longer interprets that as being the end of the string:

println!("I am John \"the coder\" Doe");

The output of this code is:

I am John "the coder" Doe

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

println!("C:\Desktop\Games");

This code looks perfectly fine at first sight, but it does not compile. The compiler reports this error for each backslash:

error: unknown character escape: `D`

That's because in Rust, \ is also a special character and its main purpose is escaping other characters, not being printed.

So when the compiler sees \D for example, it supposes that you are trying to escape character D, but \D is not a valid escape sequence, so it reports an error.

Like any special character, \ can also be escaped by putting another \ in front of it (\\):

println!("C:\\Desktop\\Games");

The output of this code is:

C:\Desktop\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

print!("Hello world!\nWhat a good day for coding!\n");
print!("Let's have a blast!");

The output of this code is:

Hello world!
What a good day for coding!
Let's have a blast!

Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    RUST · STRINGS I

    Escaping Characters in Rust, explained

    What escaping is

    Some characters have a job inside a string literal. The double quote marks where the literal starts and ends, and the backslash begins an escape sequence. When you want one of these characters to appear as ordinary text, or want to write a character you can't type directly, such as a line break, you write a backslash followed by a code. Rust reads the two characters together and produces a single character in the string.

    The escapes you will use most often are:

    EscapeProduces
    \"a double quote
    \\one backslash
    \na new line
    \ta tab
    \'a single quote (needed in a char literal, optional in a string)
    \u{e9}the character with that Unicode code point, here é

    Quotes inside a string

    Suppose you want to print I am John "the coder" Doe. Writing the quotes as they are does not work:

    println!("I am John "the coder" Doe");
    

    The literal ends at the second quote, so the text the coder is no longer inside a string, and the program does not compile. The compiler complains about an unknown prefix and an expected comma. Putting a backslash before each inner quote tells Rust that the quote is part of the text:

    println!("I am John \"the coder\" Doe");
    
    I am John "the coder" Doe
    

    A single quote inside a double-quoted string needs no escape: "Let's go" is fine.

    Printing a backslash

    Because the backslash starts an escape, a lone backslash is an error in Rust. Rust accepts only a fixed set of escape sequences, and anything else is rejected when the program is compiled. This line does not build:

    println!("C:\Desktop\Games");
    

    The compiler reports unknown character escape: `D` and then the same for G. To print a real backslash, double it:

    println!("C:\\Desktop\\Games");
    
    C:\Desktop\Games
    

    New lines

    The same mechanism gives meaning to an ordinary letter. A backslash before n is a line break:

    print!("Hello world!\nWhat a good day for coding!\n");
    print!("Let's have a blast!\n");
    
    Hello world!
    What a good day for coding!
    Let's have a blast!
    

    println! adds a line break after its output by itself, while print! does not. That is why the examples above end their text with \n when they use print!.

    Raw strings

    When a text has many backslashes or quotes, Rust offers a way to skip escaping altogether: a raw string, written with an r before the opening quote. Nothing inside it is treated as an escape:

    println!("{}", r"C:\Users\Andy\notion");
    println!("{}", r#"He said "hi""#);
    
    C:\Users\Andy\notion
    He said "hi"
    

    If the text itself contains a double quote, add one or more # characters on each side of the quotes, as in the second line. The lesson uses ordinary escapes, but raw strings are the tool to reach for when a path or a pattern is full of backslashes.

    A note on {}

    The text passed to println! is a format string, so it has one more special pair of characters: { and }. To print a literal brace, double it: println!("{{}} braces {}", 5) prints {} braces 5. Passing a message as an argument, as in println!("{}", message), avoids the problem, because the message is inserted as it is and its braces are not interpreted.

    The lesson's exercise

    The exercise has three prints, each using one of the ideas above.

    1. Quotes. The message I'll study "Coding 101" on AlgoCademy goes in as the second argument of println!("{}", ...). The inner double quotes are escaped as \". The apostrophe in I'll needs nothing.
    2. Two lines from one statement. A \n between the two phrases splits them into separate lines.
    3. A file path. Each backslash in C:\Users\Andy\notion is doubled so that it prints as one backslash.
    println!("{}", "I'll study \"Coding 101\" on AlgoCademy");
    println!("I will learn this\nNo matter what");
    println!("C:\\Users\\Andy\\notion");
    

    Key takeaways

    • A backslash followed by a code is an escape sequence; the pair becomes one character.
    • Use \" for a double quote inside a string and \\ for a backslash.
    • An unknown escape such as \D is a compile error in Rust, not a silently dropped character.
    • \n starts a new line; println! already adds one at the end, and print! does not.
    • A raw string, r"...", turns escapes off.
    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free