实现说明
核心动作集中在函数 describe、main中。
使用要点
- 每一步打印都带着自己的标签:
field:、body:、normal:。 main按顺序串起describe;运行文件就会把这个流程跑一遍。
常见问题
运行「原始标识符让关键字作名字」会打印什么?
整个文件跑完,输出行以 field:、body:、normal: 这类前缀开头。
主签名形如 fn describe(r#type: &str) -> String
核心语句
fn describe(r#type: &str) -> String {
format!("kind={type}")
}
代码示例
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}");
}