#[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@ltpp.vip".to_string());
assert_eq!(user.username, "alice");
assert_eq!(user.email, "alice@ltpp.vip");
assert_eq!(user.created_at, "");§With Custom Visibility
use lombok_macros::*;
#[derive(New)]
#[new(pub(crate))]
struct InternalStruct {
value: i32,
}
let internal = InternalStruct::new(42);
assert_eq!(internal.value, 42);§Tuple Structs
use lombok_macros::*;
#[derive(New)]
struct Point(
f64,
f64,
);
let origin = Point::new(0.0, 0.0);
assert_eq!(origin.0, 0.0);
assert_eq!(origin.1, 0.0);§Generic Types
use lombok_macros::*;
#[derive(New)]
struct Container<T: Default + Clone> {
data: T,
#[new(skip)]
count: usize,
}
let container = Container::new("data".to_string());
assert_eq!(container.data, "data");
assert_eq!(container.count, 0);§Arguments
input- The input token stream representing the struct for which to generate the constructor.
§Returns
TokenStream- The generated constructor implementation.