Start learning free

LESSON 57 OF 348 · STRINGS I

Escaping characters in Rust in Rust

Lesson

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 .

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 if you run it, it would produce this output:

C:DesktopGames

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

So when the interpreter sees \C for example, it supposes that you are trying to escape character C, which is not a special character thus it's already "escaped".

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

    Escaping Characters in Rust

    Keep going with RustAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free