SmartDefault
A custom derive for Rust's Default trait with per-field control over default values.
Repository Health
Technical Analysis
smart-default is a Rust procedural macro that derives the standard Default trait while giving you fine-grained control over each field’s default value. Instead of relying on Default::default() for every field, you annotate fields with attributes to supply literals, expressions, or arbitrary code, and you can mark which enum variant is the default. It builds on syn, quote, and proc-macro2 to generate clean Default implementations.
What You Get
- A
SmartDefaultderive macro that implements the standardDefaulttrait - Per-field
#[default = ...]attributes for literals and simple values - Expression and raw-code defaults via
#[default(...)]and the_codeform - A
#[default]marker to select which enum variant is the default - Generated code that integrates transparently with any code expecting
Default
Common Use Cases
- Deriving Default when some fields need non-zero or computed initial values
- Choosing a specific default variant for a configuration enum
- Building ergonomic default configuration or builder-style structs
Under The Hood
Architecture
As a procedural macro crate, its entry point is src/lib.rs, which defines the SmartDefault derive and parses the input type with syn. src/default_attr.rs interprets the #[default] and #[default(...)] attributes on fields and enum variants, src/body_impl.rs generates the resulting Default implementation via quote, and src/util.rs provides shared token helpers. The output is an ordinary impl Default for the annotated type.
Tech Stack
It targets Rust edition 2021 with a minimum rust-version of 1.56 and is declared as a proc-macro library. It depends on the standard procedural-macro trio: syn 2 for parsing, quote for code generation, and proc-macro2 for token handling.
Code Quality
Tests live in tests/tests.rs and validate the generated defaults across literals, expressions, raw code, and enum variant selection, and the examples/ directory demonstrates real usage. The clear separation between attribute parsing and code generation keeps the macro logic maintainable, and the crate has a long, stable release history.
API Design
Usage is a single #[derive(SmartDefault)] plus intuitive #[default = ...] and #[default(...)] attributes placed right next to the fields they configure, which keeps defaults local and readable. The README’s annotated example covers literals, wrapped expressions, the _code escape hatch, and enum defaults, so the full feature set is easy to discover.