作用
通过派生宏 #[derive(With)] 给结构体字段生成 with_xxx 方法,通过链式调用 with_xxx 方法来构造结构体。
使用方法
1.给 named struct 每个字段生成 with_xxx 方法
#[derive(With)] pubstructFoo{ puba:i32, pubb:String, }
宏生成代码
implFoo{
pubfnwith_a(mutself,a:implInto)->Self{
self.a=a.into();
self
}
pubfnwith_b(mutself,b:implInto)->Self{
self.b=b.into();
self
}
}
2.给 tuple struct 每个字段生成 with_xxx 方法
#[derive(With)] pubstructBar(i32,String);
宏生成代码
implBar{
pubfnwith_0(mutself,field_0:implInto)->Self{
self.0=field_0.into();
self
}
pubfnwith_1(mutself,field_1:implInto)->Self{
self.1=field_1.into();
self
}
}
3.通过字段名给 named struct 指定字段实现 with_xxx 方法
#[derive(With)]
#[with(a)]
pubstructFoo{
puba:i32,
pubb:String,
}
宏生成代码
implFoo{
pubfnwith_a(mutself,a:implInto)->Self{
self.a=a.into();
self
}
}
4.通过下标给 tuple struct 指定字段生成 with_xxx 方法
#[derive(With)] #[with(1)] pubstructBar(i32,String);
宏生成代码
implBar{
pubfnwith_1(mutself,field_1:implInto)->Self{
self.1=field_1.into();
self
}
}
也支持结构体中含有泛型、生命周期、引用等。
审核编辑:刘清
-
rust语言
+关注
关注
0文章
57浏览量
3243
原文标题:【大家的项目】利用 Rust 过程宏实现的 derive-with 库
文章出处:【微信号:Rust语言中文社区,微信公众号:Rust语言中文社区】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录
如何在Rust中连接和使用MySQL数据库
如何使用Serde进行序列化和反序列化
如何使用Rust的标准库和structopt库来处理控制台参数
如何利用C语言去调用rust静态库呢
在Rust代码中加载静态库时,出现错误 ` rust-lld: error: undefined symbol: malloc `怎么解决?
Rust 1.15 引入自定义derive特性有什么做用
Rust GUI 库发展现状
Chromium正式开始支持Rust
为什么我们从C++语言转向Rust语言呢?
基于Rust的Log日志库介绍
Rust的标准库的功能划分

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