百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
R

rust-derive-macro-guide

> 编程语言
开源

Rust 中的简单导出宏

192 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

Rust 中的简单导出宏

#[derive(MyTrait)]

A copypastable guide to implementing simple derive macros in Rust.

The goal

Let's say we have a trait with a getter

rust
trait MyTrait {
    fn answer() -> i32 {
        42
    }
}

And we want to be able to derive it and initialize the getter

rust
#[derive(MyTrait)]
struct Foo;

#[derive(MyTrait)]
#[my_trait(answer = 0)]
struct Bar;

#[test]
fn default() {
    assert_eq!(Foo::answer(), 42);
}

#[test]
fn getter() {
    assert_eq!(Bar::answer(), 0);
}

So these derives would expand into

rust
impl MyTrait for Foo {}

impl MyTrait for Bar {
    fn answer() -> i32 {
        0
    }
}

Step 0: prerequisites

Install Cargo extended tools

bash
cargo install cargo-edit
cargo install cargo-expand

Step 1: a separate crate for the macro

Proc macros should live in a separate crate. Let's create one in a sub-folder and make it a dependency for our root crate

bash
cargo new --lib mytrait-derive
cargo add mytrait-derive --path mytrait-derive

We should also tell Cargo that mytrait-derive is a proc-macro crate:

bash
cat >> mytrait-derive/Cargo.toml  TokenStream {
    let DeriveInput { ident, .. } = parse_macro_input!(input);
    let output = quote! {
        impl MyTrait for #ident {}
    };
    output.into()
}

You can think of ident as a name of a struct or enum we're deriving the implementation for. We're getting it from the parse_macro_input! and then we use it in the quote!, which is like a template engine for Rust code generation.

Now this test (src/lib.rs) should pass:

rust
use mytrait_derive::MyTrait;

trait MyTrait {
    fn answer() -> i32 {
        42
    }
}

#[derive(MyTrait)]
struct Foo;

#[test]
fn default() {
    assert_eq!(Foo::answer(), 42);
}

Also you should be able to find the implementation in the output of cargo-expand

bash
cargo expand | grep 'impl MyTrait'
impl MyTrait for Foo {}

Step 3: the getter initialization

Now it's time to make our getter initializable by #[my_trait(answer = ...)] attribute. We'll need one more crate for convenient parsing of the initialization value

bash
cd mytrait-derive
cargo add [email protected]

Here's the final version of our macro (mytrait-derive/src/lib.rs):

…

Struct Opts describes parameters of the #[my_trait(...)] attribute. Here we have only one of them - answer. Notice that it's optional, because we don't want to overwrite the default fn answer() implementation if the attribute wasn't used.

The quote! macro is composable - we can use output of one of them in another. So in the match we check if the initializer is passed and create the method implementation or just nothing. And finally we use the result in the outer quote! template.

That's all, clone this repo to play with the code.

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rust

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言