expression

Manual Deserialize implementation

Delegate parsing to a known type and enforce an invariant before constructing a domain value. Errors are reported through the active format. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 4 true Common mistake: Allowing a parsed primitive to bypass domain invariants.

Formal Syntax & Structure

rust syntaxrust
impl<'de> serde::Deserialize<'de> for T

Working Example

Example Snippetrust
fn main() {    struct Rating(u8);    impl<'de> serde::Deserialize<'de> for Rating {        fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {            let n = <u8 as serde::Deserialize>::deserialize(d)?;            if (1..=5).contains(&n) { Ok(Self(n)) }            else { Err(serde::de::Error::custom("rating outside 1..=5")) }        }    }    println!("{}", serde_json::from_str::<Rating>("4").unwrap().0);    println!("{}", serde_json::from_str::<Rating>("0").is_err());}
Rust Reference