Rust Clone With
Description
A rust procedural macro that allows you to clone a struct with a subset of its fields.
Adds a with_{field_name}
method for each field in the struct.
Configuration
[dependencies]
clone_with = "0.1.0"
Usage
use clone_with::CloneWith;
#[derive(Debug, Clone, CloneWith)]
struct MyStruct {
id: u32,
name: String,
has_a_pet: bool,
}
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);
}
For the MyStruct struct, the following code is generated by the macro:
use clone_with::CloneWith;
#[derive(Debug, Clone, CloneWith)]
struct MyStruct {
id: u32,
name: String,
has_a_pet: bool,
}
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
}
}