网站首页 > 博客文章 正文
作用
通过派生宏 #[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<i32>) -> Self {
self.a = a.into();
self
}
pub fn with_b(mut self, b: impl Into<String>) -> 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<i32>) -> Self {
self.0 = field_0.into();
self
}
pub fn with_1(mut self, field_1: impl Into<String>) -> 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<i32>) -> 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<String>) -> Self {
self.1 = field_1.into();
self
}
}
也支持结构体中含有泛型、生命周期、引用等。
github: https://github.com/systemxlabs/derive-with
猜你喜欢
- 2024-09-11 Rust 写操作系统之Hello world (三)
- 2024-09-11 Rust: 如何用Panic打造健壮应用(rust zig)
- 2024-09-11 在 Linux 新版内核中的 Rust 初探,原来是这样的
- 2024-09-11 Rust 向量(Vec)(rust 向量化)
- 2024-09-11 Rust 入坑指南:鳞次栉比 | CSDN 博文精选
- 2024-09-11 学习Rust编程——使用macro_rules!创建宏
- 2024-09-11 Rust 基础入门-错误处理和宏-错误处理
- 2024-09-11 Rust 基础入门-错误处理和宏-属性式宏&函数式宏
- 2024-09-11 Rust中巧用matches!宏(rust腐蚀免费版)
- 2024-09-11 Rust编程语言里的宏回调(rust宏数据)
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- powershellfor (55)
- messagesource (56)
- aspose.pdf破解版 (56)
- promise.race (63)
- 2019cad序列号和密钥激活码 (62)
- window.performance (66)
- qt删除文件夹 (72)
- mysqlcaching_sha2_password (64)
- ubuntu升级gcc (58)
- nacos启动失败 (64)
- ssh-add (70)
- jwt漏洞 (58)
- macos14下载 (58)
- yarnnode (62)
- abstractqueuedsynchronizer (64)
- source~/.bashrc没有那个文件或目录 (65)
- springboot整合activiti工作流 (70)
- jmeter插件下载 (61)
- 抓包分析 (60)
- idea创建mavenweb项目 (65)
- vue回到顶部 (57)
- qcombobox样式表 (68)
- vue数组concat (56)
- tomcatundertow (58)
- pastemac (61)
本文暂时没有评论,来添加一个吧(●'◡'●)