Skip to main content

diff

Function diff 

Source
pub fn diff<T: Serialize>(old: &T, new: &T) -> Result<Value, Error>
Expand description

Computes a JSON diff suitable for use as a Merge Patch (RFC 7396).

Returns a serde_json::Value containing only changed fields (with new values). If no changes, returns an empty object.

See also diff_including for a version that can force inclusion of specific fields.

§Example

use serde_json::json;

#[derive(serde::Serialize)]
struct User { id: u32, name: String, age: u8 }

let old = User { id: 1, name: "old".to_string(), age: 31 };
let new = User { id: 1, name: "new".to_string(), age: 31 };

let patch = serde_patch::diff(&old, &new).unwrap();
assert_eq!(patch, json!({ "name": "new" }));
Examples found in repository?
examples/full.rs (line 42)
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}