-
-
Notifications
You must be signed in to change notification settings - Fork 7
Derive macro to derive Default from Serde default attributes #4
Comments
Is the advantage of this over the reverse (hand-implementing Apart from that performance gain, my gut reaction is that it's more idiomatic to be explicit about the default and let serde pick that up. |
For reference, linking colin-kiegel/rust-derive-builder#117 |
I have a version of this mostly working, filed dtolnay/quote#95 to try and sort out some error span situations and then I'll put it up for review. |
First draft is up: https://github.com/TedDriggs/serde_default I really like the idea of declaring defaults at the field level so that proc-macro crates can fill in missing fields without creating an entire However, if multiple crates all require the same entry, then the worst case scenario becomes: #[derive(Builder, Deserialize, CustomDefault)]
pub struct MyStruct {
#[builder(default = "my_default")]
#[serde(default = "my_default")]
my_field: String,
} IMO, that hurts readability and increases the likelihood of hard-to-debug errors coming from drift between the two attributes. What if instead there was a crate that focused just on field-level defaults, using serde syntax, and any crate that wanted to read those attributes could do so? Then the code would read: #[derive(Builder, Deserialize, CustomDefault)]
pub struct MyStruct {
#[default(default = "my_default")]
my_field: String,
} serde, derive_builder, et al. could all look at that attribute and use it as a fallback for their own defaulting information. |
Thanks, nicely done! I will go ahead and close out this issue and mark it off the list, and we can follow up on any remaining work on your issue tracker.
Another advantage is in this sort of situation: #[derive(Deserialize, Default_serde)]
#[serde(default)]
struct S {
// Almost all Default::default if omitted
a: String,
b: String,
c: String,
...
// Except for
#[serde(default = "default_n")]
n: String,
} Here a handwritten What are your thoughts on the |
The following data structures accept any of the following JSON inputs when deserializing:
If there is an
"http"
entry but the"address"
is missing, Serde will use the default address. If there is an"http"
entry but the"port"
is missing, we use the default port. If"http"
is missing entirely, we use the Default impl of HttpConfig which comes with the default address and default port. This is working as intended.But notice that the Default impl is repetitive and could be inferred from the serde attributes. I would like for there to be a
Default_serde
derive macro that derives the Default trait by using the Serde default value for each field.expands to:
The text was updated successfully, but these errors were encountered: