Skip to content

Add a SerializeOwned trait for owning serialization #3011

@cactusdualcore

Description

@cactusdualcore

TL;DR: Serialize::serialize takes values by reference but a lot of the time they are thrown away after serialization

I really like Rust! Especially its destructive move semantics. However, serde force a pattern for serialization which reminds me a lot of C++ move semantics. Many times have I built up a value just to serialize it to some stream, dropping it right afterwards. However, because the Serialize::serialize method takes the value by reference, any transformations to convert a value from its in-memory representation to one more suitable for storage force users into either cloning excessively or writing a lot of Boilerplate to avoid it.

I think many use cases could profit from destructive serialization.

My suggestion is a new SerializeOwned trait, such that &T: SerializeOwned where T: Serialize.

Now, the Serializer trait could add a new method serialize_owned, with a default implementation that simply panics on use (ala unimplemented!()). Implementations could then move over to the new trait and if serde ever has a major version bump, just remove the default impl and instead provide it for serialize.

This would make writing custom serialization a lot less of a pain in these cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions