Raw Identifiers Let Keywords Be Names

Use r# to name a field, variable, and function after a Rust keyword such as type, then confirm the raw syntax is only needed at definition and call sites.

RustData Integrity

Code

rustsnippet
27 lines
struct Message {
    // r# 让关键字 type 成为合法字段名
    r#type: &'static str,
    body: &'static str,
}

fn describe(r#type: &str) -> String {
    format!("kind={type}")
}

fn main() {
    let message = Message {
        r#type: "alert",
        body: "disk almost full",
    };

    // 访问 raw 字段时仍要写 r#type
    println!("field: {}", message.r#type);
    println!("body: {}", message.body);

    // 调用同样用 r# 前缀,函数内形参名不必再带 r#
    println!("{}", describe("warning"));

    // 普通标识符不需要 r#
    let normal = String::from("ok");
    println!("normal: {normal}");
}

How the snippet works

One way to read it: the functions describe and main, doing all the work.

What to watch for

  • Entirely standard-library — copy it in and it runs.

Using it

The primary signature is fn describe(r#type: &str) -> String

The demo output is labeled (field:, body:, normal:), so every printed line maps back to its originating operation.

There are 1 call inside main — describe — executed top to bottom.

Key statements

fn describe(r#type: &str) -> String {
    format!("kind={type}")
}

Interactive Tools for This Topic

FAQ

What does Raw Identifiers Let Keywords Be Names print when run?
Invoke the file as-is — the `field:`, `body:`, `normal:` prefixes identify which step printed each line.