serde-rs / serde

Serialization framework for Rust
https://serde.rs/
Apache License 2.0
9.06k stars 767 forks source link

Allow deserialize() to have a non-Self return type #2735

Closed vrurg closed 4 months ago

vrurg commented 5 months ago

Within a task I'm currently trying to solve there is a need for async structs to initialize themselves and produce not just Self but Arc<Self>. At the same time I want them to support serde when necessary. But here comes a problem because neither approach I managed to dig up with google allows to, say, serde_toml::from_str(source) return an Arc<Self>. Perhaps remote parameter can help, but I'm not sure how well would it blend with from. Besides, it introduces another, rather unnecessary, layer of abstraction with introduction of RemoteSelf<Arc<Self>>.

Instead, for something like:

#[serde(from = "__FooShadow")]
struct Foo {...}

It would be much simpler and cleaner to implement something like the following pseudo-code:

impl<'de> Deserialize<'de> for Foo {
    fn deserialize<__D>(deserializer: __D) -> Result<Arc<Self>, __D::Error> {
        let shadow = __FooShadow::deserialize(deserializer);
        let me: Arc<Self> = Self::from(shadow);
        Ok(me)
    }
}
dtolnay commented 4 months ago

It would be interesting to explore designs for this in a different serialization library, but I don't see this being something that would change in serde.