EzInit
Initialize structs easily with powerful derive macros.
How does it work?
If you derive EzInit on your struct, it will generate a new() function that initializes the struct fields based on the following rules:
Field Initialization Modes
-
Explicit Default Value:
#[init(default = <expression>)]- Uses the provided expression to initialize the field
- Example:
#[init(default = 100)],#[init(default = "hello".to_string())]
-
Default Trait:
#[init(default)]- Uses
Default::default()for types that implementDefault - Example:
#[init(default)]on a field of typeCharacterClass(if it derivesDefault)
- Uses
-
Random Values:
#[init(random)]or#[init(random = "range")]or#[init(random = [items])]#[init(random)]: Random value using the type's standard random generation#[init(random = "1..10")]: Random integer in range#[init(random = "0.0..1.0")]: Random float in range#[init(random = ["A", "B", "C"])]: Random item from list
-
Random Enum Variant:
#[init(enum)]- Picks a random variant from an enum that derives
RandomVariant - The enum must only have unit variants (no data)
- Picks a random variant from an enum that derives
-
Option Types: No attribute needed
- Automatically initialized to
None
- Automatically initialized to
-
Required Fields: No attribute
- Becomes a required parameter in the
new()function
- Becomes a required parameter in the
RandomVariant Derive
For enums, derive RandomVariant to enable random variant selection:
- Only works on enums with unit variants (no associated data)
- Can be combined with
Defaultderive for flexible initialization - Implements
Distribution<YourEnum>forrand::distributions::Standard
Installation
Not published yet, so you need to clone the repo and add it as a path dependency:
[]
= { = "path/to/ezinit" }
Usage Example
use ;
// Derive RandomVariant for random enum selection
// Derive EzInit to generate the new() function
Sample Output
Running the above code produces output like this (values marked as random will differ each run):
Highway: I-95
Type: Street (always default), Condition: Good (random)
Built by: Cat, Lanes: 2
Max Speed: 87 km/h, Length: 42.7 km
Each time you run the program, the random values will change:
Highway: I-95
Type: Street (always default), Condition: Fatal (random)
Built by: Politician, Lanes: 2
Max Speed: 103 km/h, Length: 15.3 km
Generated Code
For the above example, EzInit generates:
License
MIT