#[derive(New)]
{
// Attributes available to this derive:
#[new]
}
Expand description
A procedural macro that generates a constructor function for structs.
This macro automatically generates a new function that takes all non-skipped fields
as parameters and returns a new instance of the struct. Fields marked with #[new(skip)]
will be initialized with their default values.
§Supported Attributes
#[new(skip)]: Excludes the field from constructor parameters and uses default initialization#[new(pub)]: Generates a public constructor#[new(pub(crate))]: Generates a crate-visible constructor#[new(pub(super))]: Generates a constructor visible to parent module#[new(private)]: Generates a private constructor
§Default Behavior
- The generated constructor is
pubby default - All fields are included in the constructor unless marked with
#[new(skip)] - Skipped fields are initialized using
Default::default()
§Examples
§Basic Usage
use lombok_macros::*;
#[derive(New)]
struct Person {
name: String,
age: u32,
}
let person = Person::new("Alice".to_string(), 30);
assert_eq!(person.name, "Alice");
assert_eq!(person.age, 30);§With Skip Attribute
use lombok_macros::*;
#[derive(New)]
struct User {
username: String,
email: String,
#[new(skip)]
created_at: String,
}
let user = User::new("alice".to_string(), "alice@example.com".to_string());
assert_eq!(user.username, "alice");
assert_eq!(user.email, "alice@example.com");
assert_eq!(user.created_at, ""); // skipped field defaults to empty string§With Visibility Control
use lombok_macros::*;
#[derive(New)]
#[new(pub(crate))]
struct InternalStruct {
value: i32,
}§Parameters
input: The input token stream representing the struct for which to generate the constructor.
§Returns
TokenStream: The generated constructor implementation.