0.1.0 |
|
---|
#27 在 #changed
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
}
}
依赖项
~255–700KB
~17K SLoC