Derive Macro struct_patch::Patch

source ·
#[derive(Patch)]
{
    // Attributes available to this derive:
    #[patch_derive]
    #[patch_name]
}
Expand description

Patch help you patch Rust instance, and easy to partial update.

 #[derive(Patch)]
 struct Item {
    field_bool: bool,
    field_int: usize,
    field_string: String,
  }

Patch derive will generate ItemPatch and implement Patch trait for struct.

#[derive(Default)]
 struct ItemPatch {
    field_bool: Option<bool>,
    field_int: Option<usize>,
    field_string: Option<String>,
 }

Such that you can use apply function to patch the existing fields from ItemPatch to Item, and use is_empty to check the patch instance has something to patch or not.

use struct_patch::traits::Patch;
let mut item = Item::default();
let mut patch = Item::new_empty_patch();
assert(patch.is_empty());

patch.field_int = Some(7);
assert!(!patch.is_empty());

item.apply(patch); // only `field_int` updated

patch_derive

If you want to add more derives on patch struct, you can use patch_derive as following.

 #[derive(Patch)]
 #[patch_derive(Debug, Default, Deserialize, Serialize)]
 struct Item { }

Patch derive will generate ItemPatch and implement Patch trait for struct.

#[derive(Debug, Default, Deserialize, Serialize)]
 struct ItemPatch {}

patch_name

If you want to change the patch struct name, you can use patch_name as following.

 #[derive(Patch)]
 #[patch_name=ItemOverlay]
 struct Item { }

Patch derive will generate ItemOverlay and implement Patch trait for struct.

 struct ItemOverlay{}

New a patch

You can get a patch by diff on two instances

let item = Item::default();
let new_item = Item {
    field_int: 7,
    ..Default::default()
};

let patch =  new_item.into_patch_by_diff(item);

Such that the patch struct can easily generated from json or other serializer. Please check the example.