Description
I've found myself implementing my own proc macro to use a trait something like this:
pub trait KnownKey {
fn key() -> &'static str;
}
that is then used to replace field names, e.g.
pub struct KnownThing;
impl KnownKey for Known Thing {
fn key() -> &'static str { "example string" }
}
pub struct ContainsStuff {
#[serde(rename = "example string")]
first_thing: KnownThing;
#[serde(rename = "see the duplication here?")]
second_thing: AnotherKnownThing;
}
But ofc since I can't pass the function key
to the serde rename macro, and I'm preparing to have hundreds of similar structs, I'm having to manually implement implement Serialize
and Deserialize
through a custom macro.
Implementing serialize isn't that hard to do by hand, kinda like using .debug_struct(), but Deserialize
is kinda a pain.
Proposed additions
A new syntax (or not if you can get it to be backwards compatible) surrounding the #[serde(rename)]
attribute, e.g. #[serde(rename(expr = "KnownThing::key()")]
, that is an expression that evaluates to &'static str
.
Past efforts
Before building a proc macro, I spent a while looking through past issues, notably this one: #1686 which was closed by dtolnay with the (chad move):
But if someone wanted to put together a more fully featured derive macro as a separate library, I think that would be welcome
Well, I'm building that macro, and I can tell you its almost trivial to eagerly evaluate the function once or at each usage site with my current use cases. Mind you, I don't use all the attribute combinations of serde, but even if some combination of attributes makes this harder or non-trivial, it would still be greatly appreciated for this to exist for the simple cases like shown above!
I can try to make a PR for this, but I'm no serde
expert and wanted to hear what was to be said on this issue before I spend any more time over-engineering things