Skip to main content

apply_mut

Function apply_mut 

Source
pub fn apply_mut<T, P>(current: &mut T, patch: P) -> Result<(), Error>
where T: Serialize + DeserializeOwned, P: AsRef<[u8]>,
Expand description

Applies a JSON Merge Patch (RFC 7396) in-place.

Modifies the current value directly.

§Example

#[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]
struct User { id: u32, name: String }

let mut user = User { id: 1, name: "old".to_string() };
let patch = r#"{ "name": "new" }"#;

serde_patch::apply_mut(&mut user, patch).unwrap();
assert_eq!(user.name, "new");
assert_eq!(user.id, 1);
Examples found in repository?
examples/full.rs (line 55)
18fn main() -> Result<(), Box<dyn std::error::Error>> {
19    let old = User {
20        id: 1001,
21        username: "alice".to_string(),
22        age: 30,
23        active: true,
24        profile: Some(Profile {
25            bio: "Software engineer".to_string(),
26            avatar_url: Some("https://example.com/alice-old.jpg".to_string()),
27        }),
28    };
29
30    let new = User {
31        id: 1001,
32        username: "alice".to_string(),
33        age: 31,
34        active: false,
35        profile: Some(Profile {
36            bio: "Senior software engineer".to_string(),
37            avatar_url: None,
38        }),
39    };
40
41    // Basic diff – only changed fields
42    let basic_patch = serde_json::to_string(&serde_patch::diff(&old, &new)?)?;
43    println!("Basic patch (no forced fields):\n{}", basic_patch);
44
45    // Diff with forced field – includes "id" even though unchanged
46    let forced_patch = serde_json::to_string(&serde_patch::diff_including(&old, &new, &["id"])?)?;
47    println!("\nPatch with forced \"id\":\n{}", forced_patch);
48
49    // Apply immutably
50    let updated = serde_patch::apply(old.clone(), &basic_patch)?;
51    println!("\nImmutable apply result:\n{:#?}", updated);
52
53    // Apply mutably
54    let mut current = old;
55    serde_patch::apply_mut(&mut current, &forced_patch)?;
56    println!("\nMutable apply result:\n{:#?}", current);
57
58    assert_eq!(updated, new);
59    assert_eq!(current, new);
60
61    Ok(())
62}