EmbarkStudios / mirror-mirror

🪞 Powerful reflection library for Rust
Apache License 2.0
79 stars 2 forks source link

Use `Default` for `default_value` #135

Closed maxded closed 6 months ago

maxded commented 6 months ago

Checklist

Description of Changes

Currently, TypeDescriptor::default_value doesn't respect the Default implementation and instead uses the default for each individual field. These changes address that problem by making structs, tuple structs, and enums properly return their Default for default_value if it is implemented for that type.

This is achieved by making #[derive(Reflect)] assume that Default is implemented, which a user can opt out of through #[reflect(opt_out(Default))]. The opt out strategy was chosen over an opt in strategy as Clone and Debug follow opt out as well. This is a breaking change to the APIs!

The default Value for a struct, tuple struct, or enum is cached inside their node. This is needed due to serialization support. If I understand correctly, each node is unique in its TypeGraph but not globally unique. This means that the default value for a struct will be duplicated across TypeGraphs. I think that improving the duplication between nodes is a good separate optimization step.

Note that this PR focuses on resolving the linked issue. There should probably be further discussions on the design behind default values and what type of APIs to expose to interact nicely with it.

Related Issues