Raw String Literals Skip Escapes

Write backslashes and quotes verbatim with raw string literals, using # delimiters when quotes appear, for regexes, JSON fixtures and Windows paths.

RustCli Tooling

Code

rustsnippet
18 lines
fn main() {
    // r"..." 原始字符串:反斜杠按字面保留,正则与路径不用双写
    let pattern = r"\d{4}-\d{2}-\d{2}";
    println!("pattern: {pattern}");

    // 内容含引号时用 # 定界:r#"..."# 内部的 " 不需要转义
    let json = r#"{"service":"orders","replicas":3}"#;
    println!("json: {json}");

    // 尾部反斜杠在原始字符串里合法:普通字符串会变成转义引号
    let path = r"C:\logs\app\";
    println!("path: {path}");

    // 原始字符串仍是 &str:可比较、可取长度
    let same = r"plain text";
    assert_eq!(same, "plain text");
    println!("same: {same} ({})", same.len());
}

Line-by-line reading

Everything happens inside the function main.

Watch out for

  • Copy, run: the standard library answers every call in the file.

Using it

Entry signature: fn main()

The file’s steps show up in the output as pattern:, json:, path:.

Key statements

let json = r#"{"service":"orders","replicas":3}"#;
let pattern = r"\d{4}-\d{2}-\d{2}";
assert_eq!(same, "plain text");

Interactive Tools for This Topic

FAQ

What does Raw String Literals Skip Escapes print when run?
Execute the whole file; each printed line is prefixed with a label like `pattern:`, `json:`, `path:`.