serde-rs / serde-rs.github.io

https://serde.rs
Creative Commons Attribution Share Alike 4.0 International
22 stars 96 forks source link

Document serde(try_from = "...") container attribute #99

Closed dtolnay closed 5 years ago

dtolnay commented 5 years ago

Implemented in https://github.com/serde-rs/serde/pull/1526, released in 1.0.97.

#[derive(Deserialize)]
#[serde(try_from = "u32")]
enum N {
    Zero,
    One,
    Two,
}

impl TryFrom<u32> for N {
    type Error = String;

    fn try_from(u: u32) -> Result<Self, Self::Error> {
        match u {
            0 => Ok(Self::Zero),
            1 => Ok(Self::One),
            2 => Ok(Self::Two),
            other => Err(format!("out of range: {}", other)),
        }
    }
}