Token导航 LogoToken导航TokenDH.com
开发只读github未标认证来源可访问许可证需确认审计通过

rust-macroRust macro 命令行

Agent Skill

rust-macro 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

240

周安装

10

GitHub Stars

29

下载量

80
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:rust-macro(Rust macro 命令行)
来源仓库:https://github.com/huiali/rust-skills
仓库路径:skills/rust-macro
安装命令:
npx skills add https://github.com/huiali/rust-skills --skill rust-macro
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/huiali/rust-skills --skill rust-macro

简介

用于处理 GitHub 仓库、Issue 和 Pull Request 协作信息。

  • 适合围绕代码变更和仓库状态进行整理与查询。
  • 可结合原始 README 进一步核验具体用法。
  • 安装前建议确认权限范围和是否会触发命令执行。
  • 需注意维护状态和网络访问限制。rust-macro 属于开发类 Skill,可作为该场景下的辅助能力补充。

SKILL.md

Macros vs Generics

DimensionMacrosGenerics
FlexibilityCode transformationType abstraction
Compile costIncremental-friendlyMonomorphization overhead
Error messagesCan be crypticClear
DebuggingDebug expanded codeDirect debugging
Use caseReduce boilerplateGeneric algorithms

Solution Patterns

Pattern 1: Declarative Macro (macro_rules!)

// Basic structure
macro_rules! my_vec {
    // Empty case
    () => {
        Vec::new()
    };
    // List of elements
    ($($elem:expr),* $(,)?) => {{
        let mut v = Vec::new();
        $(
            v.push($elem);
        )*
        v
    }};
    // Repeated element
    ($elem:expr; $n:expr) => {
        vec![$elem; $n]
    };
}

// Usage
let v1 = my_vec![];
let v2 = my_vec![1, 2, 3];
let v3 = my_vec![0; 10];

Pattern 2: Derive Macro

// In a separate proc-macro crate
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};

#[proc_macro_derive(Builder)]
pub fn derive_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = &input.ident;
    let builder_name = format!("{}Builder", name);
    let builder_ident = syn::Ident::new(&builder_name, name.span());

    let fields = match &input.data {
        syn::Data::Struct(data) => &data.fields,
        _ => panic!("Builder only works on structs"),
    };

    let field_names: Vec<_> = fields.iter()
        .filter_map(|f| f.ident.as_ref())
        .collect();

    let field_types: Vec<_> = fields.iter()
        .map(|f| &f.ty)
        .collect();

    let expanded = quote! {
        pub struct #builder_ident {
            #(#field_names: Option<#field_types>),*
        }

        impl #builder_ident {
            pub fn new() -> Self {
                Self {
                    #(#field_names: None),*
                }
            }

            #(
                pub fn #field_names(mut self, value: #field_types) -> Self {
                    self.#field_names = Some(value);
                    self
                }
            )*

            pub fn build(self) -> Result<#name, String> {
                Ok(#name {
                    #(
                        #field_names: self.#field_names
                            .ok_or_else(|| format!("Field {} not set", stringify!(#field_names)))?
                    ),*
                })
            }
        }

        impl #name {
            pub fn builder() -> #builder_ident {
                #builder_ident::new()
            }
        }
    };

    expanded.into()
}

Pattern 3: Function-like Proc Macro

#[proc_macro]
pub fn sql(input: TokenStream) -> TokenStream {
    let sql_string = input.to_string();

    // Parse and validate SQL at compile time
    validate_sql(&sql_string);

    // Generate code
    quote! {
        QueryBuilder::raw(#sql_string)
    }.into()
}

// Usage:
let query = sql!("SELECT * FROM users WHERE id = ?");

Pattern 4: Attribute Macro

#[proc_macro_attribute]
pub fn cached(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    let fn_name = &input.sig.ident;
    let fn_body = &input.block;

    let expanded = quote! {
        fn #fn_name() -> Result {
            use std::sync::OnceLock;
            static CACHE: OnceLock<Result> = OnceLock::new();

            CACHE.get_or_init(|| {
                #fn_body
            }).clone()
        }
    };

    expanded.into()
}

// Usage:
#[cached]
fn expensive_computation() -> String {
    // ...
}

Repetition Patterns

SyntaxMeaning
$()Match zero or more
$($x),*Comma-separated
$($x),+At least one
$x:tyType matcher
$x:exprExpression matcher
$x:patPattern matcher
$x:identIdentifier matcher
$x:pathPath matcher
$x:ttToken tree matcher
// Example: multiple matchers
macro_rules! create_struct {
    ($name:ident { $($field:ident: $type:ty),* }) => {
        struct $name {
            $($field: $type),*
        }
    };
}

create_struct!(User {
    id: u64,
    name: String,
    email: String
});

Workflow

Step 1: Consider Alternatives

Need to reduce duplication?
  → Can generics solve it? Prefer generics
  → Need syntax transformation? Use macros
  → Need to inspect types? Derive macro
  → Need attribute? Attribute macro

Step 2: Choose Macro Type

Declarative (macro_rules!)?
  ✅ Simple pattern matching
  ✅ Quick to write
  ❌ Limited power

Procedural (proc-macro)?
  ✅ Full AST access
  ✅ Complex transformations
  ❌ Separate crate needed
  ❌ Longer compile times

Step 3: Debug Expansion

# Expand macros
cargo expand

# Expand specific function
cargo expand my_module::my_function

# Expand tests
cargo expand --test test_name

Step 4: Test Thoroughly

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_macro_expansion() {
        // Test generated code
        let result = my_macro!(input);
        assert_eq!(result, expected);
    }
}

Common Crates

CratePurpose
synParse Rust syntax
quoteGenerate Rust code
proc-macro2Token manipulation
derive-moreCommon derive macros
darlingParse macro attributes

Best Practices

PracticeReason
Try generics firstSafer, easier to debug
Keep macros simpleComplex macros hard to maintain
Document macrosUsers need to understand expansion
Test expansionEnsure correctness
Use cargo expandVisualize macro output

Review Checklist

When reviewing macro code:

  • Could this be solved with generics instead?
  • Macro expansion documented with examples
  • Error messages are helpful
  • Edge cases tested
  • Hygiene respected (no accidental captures)
  • Used cargo expand to verify output
  • Compile-time overhead acceptable
  • No unnecessary proc-macro dependency

Verification Commands

# Expand macros
cargo expand

# Expand specific module
cargo expand path::to::module

# Check proc-macro crate
cargo check -p my-proc-macro

# Test expansion
cargo test --all-features

Common Pitfalls

1. Hygiene Violations

Symptom: Unexpected variable captures

// ❌ Bad: name clash risk
macro_rules! bad_macro {
    ($x:expr) => {{
        let result = $x;  // 'result' might clash
        result
    }};
}

// ✅ Good: use unique names
macro_rules! good_macro {
    ($x:expr) => {{
        let __macro_result = $x;
        __macro_result
    }};
}

2. Complex Error Messages

Symptom: Users don't understand macro errors

// ✅ Good: helpful error messages
macro_rules! require_trait {
    ($t:ty) => {
        const _: fn() = || {
            fn assert_impl<T: MyTrait>() {}
            assert_impl::<$t>();
        };
    };
}

3. Proc Macro Compile Time

Symptom: Slow incremental builds

// ❌ Avoid: heavy proc macros for simple tasks
#[derive(HeavyProcMacro)]
struct Simple {
    field: String,
}

// ✅ Better: manual impl or simpler derive
impl Simple {
    // Manual implementation
}

Related Skills

  • rust-coding - Naming macro conventions
  • rust-performance - Macro compile-time cost
  • rust-type-driven - When generics suffice
  • rust-error - Error handling in macros
  • rust-testing - Testing macro expansion

Localized Reference

  • Chinese version: SKILL_ZH.md - 完整中文版本,包含所有内容

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

33.9%
按下载量换算27

Claude

29.9%
按下载量换算24

Cursor

20.03%
按下载量换算16

Gemini CLI

8.95%
按下载量换算7

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

只读

该 Skill 主要提供规则、说明或参考内容,本身偏只读;真正读写文件、联网或执行命令仍取决于宿主 Agent 的任务。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills