Use raw string literals (prefixed with r) when you need to include many backslashes or quotes without escaping them, as the content between the delimiters is treated literally. You can nest multiple hashes (#) around the r and the closing quote to include the sequence " or r# inside the string itself.
Here is a practical example comparing a standard string with a raw string for a Windows file path and a regex pattern:
fn main() {
// Standard string requires escaping backslashes
let standard_path = "C:\\Users\\Dev\\project\\src\\main.rs";
// Raw string treats backslashes literally
let raw_path = r"C:\Users\Dev\project\src\main.rs";
// Standard string requires escaping double quotes
let standard_json = "{\"key\": \"value\", \"nested\": \"test\"}";
// Raw string handles quotes naturally
let raw_json = r#"{"key": "value", "nested": "test"}"#;
println!("Standard: {}", standard_path);
println!("Raw: {}", raw_path);
// Handling the delimiter itself (r#") requires more hashes
let contains_hash = r##"This string contains r#" inside it."##;
println!("Nested: {}", contains_hash);
}
If your string content contains the exact delimiter you are using (e.g., r"..." containing "), you must increase the number of hashes on both sides. The number of hashes must match exactly on the opening and closing delimiters. For instance, if your text contains r#", you must use r##"..."##. There is no limit to the number of hashes you can use, allowing you to embed any sequence of characters.
Raw strings are particularly useful for embedding SQL queries, regular expressions, or JSON payloads directly in your code, significantly improving readability. However, remember that raw strings do not support escape sequences like \n or \t; if you need actual newlines or tabs, you must type them literally or use a standard string.
# Example: Using raw strings in a build script to avoid shell escaping issues
# In build.rs
println!("cargo:rustc-env=REGEX_PATTERN={}", r#"^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[\w-]{2,}$"#);
This approach eliminates the need for complex escaping logic when dealing with platform-specific paths or complex pattern matching rules.