Rust: Raw string literals

While working with Rust, you will often come across r#"something like this"#, especially when working with JSON and TOML files. It defines a raw string literal. When would you use a raw string literal and what makes a valid raw string literal?

When would you use a raw string literal?

Escaping double-quotes can be cumbersome in some cases such as writing regular expressions or defining a JSON object as a string literal. In these situations, raw string literals are helpful since they allow you to write the literal without requiring escapes.

Here is a snippet from the toml³ crate:

Or another from serde-rs⁴:

So, raw string literals are helpful, but what makes a valid one?

What makes a raw string literal?

Escape characters in the raw string body are not processed.

Therefore the following raw string literals are all valid:

Try it on playpen

If you need to include double-quote character in a raw string, you must tag the start and end of the raw string with hash/pound signs(#).

Try it on playpen

The raw string body can contain any sequence of UNICODE characters except "# since it would terminate the literal. If you want to include the particular sequence, you have to change the number of # that precede the opening double-quote. For instance:

Try it on playpen

Likewise, if "## is to be included, you can add another # to the starting and ending delimiters.

Wrap Up

Here’s how visualising⁷ raw string literals works for me:

That’s it for now!

Enjoyed this post?

Lifelong Learner 📖

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store