Skip to main content

diff_including

Function diff_including 

Source
pub fn diff_including<T: Serialize>(
    old: &T,
    new: &T,
    including: &[&str],
) -> Result<Value, Error>
Expand description

Computes a JSON diff, forcing specific fields to be included even if unchanged.

This is useful when you need to provide context (like an ID) in the patch, regardless of whether that field has changed.

§Example

use serde_json::json;

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

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

// "id" is included even though it didn't change
let patch = serde_patch::diff_including(&old, &new, &["id"]).unwrap();
assert_eq!(patch, json!({ "id": 1, "name": "new" }));
Examples found in repository?
examples/full.rs (line 46)
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}