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.
Code
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
Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.Email Address ValidatorValidate email syntax, checking the local part, domain labels, and top-level domain against common rules.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.