Skip to content

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

License

Notifications You must be signed in to change notification settings

parthspatel/rs-clone-with

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages