Derive Default for structs when all field defaults are intrinsic - #1035
Derive Default for structs when all field defaults are intrinsic#1035danieleades wants to merge 1 commit into
Conversation
When a struct has no whole-type default value and every property's default is Default::default(), the generated manual 'impl Default' is exactly what '#[derive(Default)]' produces, and trips clippy's warn-by-default 'derivable_impls' lint in consuming code (~50 warnings on the github.json test fixture alone). Add 'Default' to the derive set in that case instead of emitting the manual impl. Structs with a whole-type default value or any custom field default still get a hand-written impl, and builder-module Default impls are unchanged.
08b15a7 to
8c952fb
Compare
|
This is an interesting schism. I can see the value in relying on the Certainly when everything is behind a macro, invoking another macro seems of limited benefit. In the case e.g. where we're generating a stand-alone crate, does it make sense to have the code be more idiomatic of hand-written code? More broadly, what utility does clippy provide for generated code? In many cases, striving for clippy cleanliness seems counter-productive. |
Problem
When every property of a struct has a default and none of them are custom, the generated code emits a hand-written
impl Defaultwhose every field initializer isDefault::default(). That impl is exactly what#[derive(Default)]produces, so clippy's warn-by-defaultderivable_implslint fires on it in consuming code — roughly 50 times on the output for a large schema like thegithub.jsontest fixture. It also bloats the generated output.Fix
In
output_struct, when there is no whole-type default value and every property's default is the intrinsicDefault::default(), addDefaultto the struct's derive set instead of emitting the manual impl.Hand-written impls are kept where they carry real information:
defaultvalue,Defaultimpls (which initialize fields toOk(..)/Err(..)).Trade-offs
None behavioral — the derived impl produces identical values to the removed manual one. The golden-file diff is large but mechanical: every removed impl had all-
Default::default()initializers, and its struct gainsDefaultin the derive list.