serde icon indicating copy to clipboard operation
serde copied to clipboard

Document how to implement Deserialize without implementing Visitor

Open dtolnay opened this issue 7 years ago • 2 comments

The Visitor documentation is featured too prominently right now. Implementing Deserialize without a Visitor is maybe even more common.

impl<'de> Deserialize<'de> for Something {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let helper = Helper::deserialize(deserializer)?;
        Ok(Something::new(helper.a, helper.b))
    }
}

dtolnay avatar May 27 '18 02:05 dtolnay

For anyone stumbling on this issue, you can do the following without any complaints from rustc:

impl <'de> Deserialize<'de> for MyType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de> {
        let field0 = u32::deserialize(deserializer)?;
        let field1 = u32::deserialize(deserializer)?;
        Ok(/* ... */)
    }
}

The key is calling u32::deserialize.

samvv avatar Mar 15 '24 19:03 samvv