关于 rust-macros
面向 Rust 开发者的宏系统 Skill,介绍声明式 `macro_rules!` 和过程宏的编写。内容包括示例、片段说明符、展开工具及问题排查。
主要功能
- 01声明式宏示例
- 02过程宏模式
- 03片段说明符参考
- 04使用 cargo expand 展开宏
- 05卫生性与定义顺序排查
适用场景
- 01编写可复用的 Rust macro_rules! 辅助宏
- 02构建派生过程宏
- 03调试时检查宏展开结果
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ pluginagentmarketplace/ custom-plugin-rust --skill rust-macros安装后在 Claude Code 中输入/rust-macros确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
assets/config.yamlmacro-example.rsschema.jsonreferences/GUIDE.mdPATTERNS.mdscripts/validate.py详细介绍
Rust 宏技能
掌握 Rust 的宏系统:声明式宏(macro_rules!)和过程宏。
快速入门
声明式宏
macro_rules! vec_of_strings {
($($x:expr),* $(,)?) => {
vec![$($x.to_string()),*]
};
}
let v = vec_of_strings!["a", "b", "c"];
片段说明符
| 说明符 | 匹配内容 |
|---|---|
ident | 标识符 |
expr | 表达式 |
ty | 类型 |
pat | 模式 |
tt | 令牌树 |
literal | 字面量 |
重复
macro_rules! hashmap {
($($key:expr => $value:expr),* $(,)?) => {{
let mut map = std::collections::HashMap::new();
$(map.insert($key, $value);)*
map
}};
}
let m = hashmap! { "one" => 1, "two" => 2 };
过程宏
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", features = ["full"] }
quote = "1"
派生宏
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
quote! {
impl HelloMacro for #name {
fn hello() {
println!("Hello from {}!", stringify!(#name));
}
}
}.into()
}
调试
cargo expand # Expand all macros
cargo expand main # Expand specific
故障排除
| 问题 | 解决方案 |
|---|---|
| 卫生问题 | 使用 $crate:: |
| 顺序很重要 | 在使用前定义 |
资源
评论
支持 Markdown