1 个不稳定版本
0.1.0 | 2023年5月25日 |
---|
#1497 in 进程宏
6KB
Rust Clone With
描述
一个Rust进程宏,允许您克隆具有其部分字段的结构体。
为结构体中的每个字段添加一个 with_{field_name}
方法。
配置
[dependencies]
clone_with = "0.1.0"
用法
use clone_with::CloneWith;
#[derive(Debug, Clone, CloneWith)]
struct MyStruct {
id: u32,
name: String,
has_a_pet: bool,
}
/// Original: MyStruct { id: 0, name: "", has_a_pet: false }
/// Updated: MyStruct { id: 42, name: "John Smith", has_a_pet: false }
pub fn main() {
let original = MyStruct {
id: 0,
name: "".to_string(),
has_a_pet: false,
};
let updated = original
.with_id(42)
.with_name("John Smith".to_string());
assert_eq!(original.id, 0);
assert_eq!(original.name, "".to_string());
assert_eq!(original.has_a_pet, false);
assert_eq!(updated.id, 42);
assert_eq!(updated.name, "John Smith".to_string());
assert_eq!(updated.has_a_pet, false);
println!("Original: {:?}", original);
println!("Updated: {:?}", updated);
}
对于MyStruct结构体,以下代码由宏生成
use clone_with::CloneWith;
#[derive(Debug, Clone, CloneWith)]
struct MyStruct {
id: u32,
name: String,
has_a_pet: bool,
}
/* Generated */
impl MyStruct {
pub fn with_id(self, id: u32) -> Self {
let mut new = self.clone();
new.id = value;
new
}
pub fn with_name(self, name: String) -> Self {
let mut new = self.clone();
new.name = value;
new
}
pub fn with_has_a_pet(self, has_a_pet: bool) -> Self {
let mut new = self.clone();
new.has_a_pet = value;
new
}
}
依赖
~300–750KB
~18K SLoC