serde_path_to_error

Function serialize

Source
pub fn serialize<T, S>(
    value: &T,
    serializer: S,
) -> Result<S::Ok, Error<S::Error>>
where T: ?Sized + Serialize, S: Serializer,
Expand description

Entry point for tracking path to Serialize error.

ยงExample

use serde::Serialize;
use std::cell::RefCell;

#[derive(Serialize)]
struct Outer<'a> {
    k: Inner<'a>,
}

#[derive(Serialize)]
struct Inner<'a> {
    refcell: &'a RefCell<String>,
}

let refcell = RefCell::new(String::new());
let value = Outer {
    k: Inner { refcell: &refcell },
};

// A RefCell cannot be serialized while it is still mutably borrowed.
let _borrowed = refcell.borrow_mut();

// Some Serializer.
let mut out = Vec::new();
let jser = &mut serde_json::Serializer::new(&mut out);

let result = serde_path_to_error::serialize(&value, jser);
match result {
    Ok(_) => panic!("expected failure to serialize RefCell"),
    Err(err) => {
        let path = err.path().to_string();
        assert_eq!(path, "k.refcell");
    }
}