Crate struct_patch

source ·
Expand description

This crate provides the Patch trait and an accompanying derive macro.

Deriving Patch on a struct will generate a struct similar to the original one, but with all fields wrapped in an Option. An instance of such a patch struct can be applied onto the original struct, replacing values only if they are set to Some, leaving them unchanged otherwise.

The following code shows how struct-patch can be used together with serde to patch structs with JSON objects.

use struct_patch::Patch;
use serde::{Deserialize, Serialize};

#[derive(Default, Debug, PartialEq, Patch)]
#[patch_derive(Debug, Default, Deserialize, Serialize)]
struct Item {
    field_bool: bool,
    field_int: usize,
    field_string: String,

fn patch_json() {
    let mut item = Item {
        field_bool: true,
        field_int: 42,
        field_string: String::from("hello"),

    let data = r#"{
        "field_int": 7

    let patch: ItemPatch = serde_json::from_str(data).unwrap();


        Item {
            field_bool: true,
            field_int: 7,
            field_string: String::from("hello")

More details on how to use the the derive macro, including what attributes are available, are available under Patch