impl-new-derive
The impl-new-derive procedural macro generates a new constructor for Rust structs. This macro automatically creates a constructor that initializes:
- Public fields from provided arguments (added as parameters to
new). - Private fields with default values using either:
- An expression specified by
#[default(...)], or Default::default()if no custom default expression is provided.
- An expression specified by
Features
- Automatically generates a
newconstructor for structs. - Handles public fields: The
newfunction takes all public fields of the struct as arguments. - Handles private fields:
- If the private field has a
#[default(...)]attribute, that expression is used for initialization. - Otherwise, the private field is initialized with
Default::default().
- If the private field has a
- Supports generic types: The macro works with both generic and non-generic structs.
Usage
-
Add the macro to your project by including it in your
Cargo.toml:[] = "0.1" -
Annotate your struct with
#[derive(ImplNew)]to automatically generate anewconstructor. Optionally, you can also deriveDefaultif needed elsewhere in your code.
Example for a Non-Generic Struct
use ImplNew;
Using #[default(...)] for Private Fields
use ImplNew;
Example for a Generic Struct
use ImplNew;
How It Works
When you annotate a struct with #[derive(ImplNew)], the macro performs the following actions:
- It iterates over the fields of the struct.
- For each public field, it adds a corresponding parameter to the generated
newmethod. - For each private field, it checks if a
#[default(expr)]attribute is present:- If yes, it uses
exprto initialize that field. - Otherwise, it uses
Default::default()to initialize that field.
- If yes, it uses
- If the struct contains generics, the macro automatically handles them in the generated
impl.
Limitations
- Only works for structs with named fields.
- If a private field doesn't implement
Defaultand does not have a#[default(...)]attribute, the macro fails to compile. - If you do use
#[default(...)], the expression inside must be a valid Rust expression for that field's type.
Contributing
Feel free to open issues or pull requests if you have any suggestions or improvements.
License
This project is licensed under the MIT License.