如何利用Rust过程宏实现derive-with库呢?

电子说

1.2w人已加入

描述

作用

通过派生宏 #[derive(With)] 给结构体字段生成 with_xxx 方法,通过链式调用 with_xxx 方法来构造结构体。

使用方法

1.给 named struct 每个字段生成 with_xxx 方法

 

#[derive(With)]
pub struct Foo {
    pub a: i32,
    pub b: String,
}

 

宏生成代码

 

impl Foo {
    pub fn with_a(mut self, a: impl Into) -> Self {
        self.a = a.into();
        self
    }
    pub fn with_b(mut self, b: impl Into) -> Self {
        self.b = b.into();
        self
    }
}

 

2.给 tuple struct 每个字段生成 with_xxx 方法

 

#[derive(With)]
pub struct Bar (i32, String);

 

宏生成代码

 

impl Bar {
    pub fn with_0(mut self, field_0: impl Into) -> Self {
        self.0 = field_0.into();
        self
    }
    pub fn with_1(mut self, field_1: impl Into) -> Self {
        self.1 = field_1.into();
        self
    }
}

 

3.通过字段名给 named struct 指定字段实现 with_xxx 方法

 

#[derive(With)]
#[with(a)]
pub struct Foo {
    pub a: i32,
    pub b: String,
}

 

宏生成代码

 

impl Foo {
    pub fn with_a(mut self, a: impl Into) -> Self {
        self.a = a.into();
        self
    }
}

 

4.通过下标给 tuple struct 指定字段生成 with_xxx 方法

 

#[derive(With)]
#[with(1)]
pub struct Bar (i32, String);

 

宏生成代码

 

impl Bar {
    pub fn with_1(mut self, field_1: impl Into) -> Self {
        self.1 = field_1.into();
        self
    }
}

 

也支持结构体中含有泛型、生命周期、引用等。



审核编辑:刘清

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分