Skip to content

Conversation

@cormacrelf
Copy link

@cormacrelf cormacrelf commented Nov 17, 2025

Fixes #1118, at least the original request. I understand some people wanted finalizers / some other kind of thing, this does not address that but I can't really see how it would be incompatible with doing that as well later. On the de side, this is just another implementation for deserialize_body, like from/try_from/transparent. Edit: indeed, seems compatible with #2891, which runs straight after deserialize_body.

I submit this PR out of light frustration, from the 100 times in the last decade that I have tried to write #[serde(with)] on a container and it hasn't existed. serde(with) modules and functions are fantastic and very reusable, and there's a whole ecosystem built around them, but they come with the silly caveat that they do not work on containers. It's silly because the pattern works on a single-variant enum, which is really just a struct, but not a struct that happens to be a container. It's an attribute that could work anywhere and function identically, but doesn't. So I think this is long overdue.

I came to this specifically after trying to tweak the serialization for a whole lot of bitflags flags. V2 of bitflags changed the serialization format to a string representation "A | B", which I have gripes with as a default, but ok. The only way to change to integer serialization for all of the bitflags is to impl Serialize and impl Deserialize on all of them, which is a lot of boilerplate. There's bitflags-serde-legacy, which would be much easier to use if only #[serde(with)] worked on containers. With this functionality, you can just write a serde-with module that's generic over T: bitflags::Flags, and you're done.

Would need docs at https://serde.rs/container-attrs.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

serde(with) for containers

1 participant