optional-default
A Helper macro to allow specifying default values for some fields of a rust struct while requiring some to be initialized manually.
Usage
Add optional-default
to your crate's dependencies: cargo add optional-default
- Annotate your struct with the
OptionalDefault
derive macro. - Annotate any optional fields with
#[optional]
. - If the field should have a default value other than
Default::default()
, or its type does not implement theDefault
trait, you can specify your own default value within the#[optional(default = <value>)]
. - The macro will generate a second macro with the same name as your struct. Use this macro to initialize the struct with your specified default values
Example
use OptionalDefault;
Limitations
Currently, the macro can only be placed on structs. While it would be possible to implement this approach for enums as well, the initialisation syntax would be inconsistent with regular enum initialisations as Enum::Variant
would not be a valid macro name.