#struct-fields #clone #proc-macro #procedural #changed #original #derive

macro clone_with

A rust procedural macro to clone a struct with some fields changed

1 unstable release

0.1.0 May 25, 2023

#1819 in Procedural macros

MIT license

6KB

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,
}

/// 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);
}

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,
}


/* 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
    }
}

Dependencies

~230–670KB
~16K SLoC