Crates.io | impl-new-derive |
lib.rs | impl-new-derive |
version | 0.1.2 |
source | src |
created_at | 2024-10-06 19:30:02.112307 |
updated_at | 2024-10-12 16:58:24.578249 |
description | Derive macro for implementing the `new` method for structs |
homepage | https://github.com/rust-dd/impl-new-derive.git |
repository | https://github.com/rust-dd/impl-new-derive.git |
max_upload_size | |
id | 1399302 |
size | 11,656 |
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 and initializes private fields with default values using the Default::default()
method.
new
) for structs.new
function takes all public fields of the struct as arguments.Default::default()
values.Cargo.toml
:[dependencies]
impl_new_derive = "0.1.0"
#[derive(ImplNew)]
to automatically generate a new
constructor.use impl_new_derive::ImplNew;
#[derive(ImplNew, Default)]
struct MyStruct {
pub name: String,
pub age: u32,
secret: String, // This field is private
}
fn main() {
let my_struct = MyStruct::new("John".to_string(), 30);
println!("Name: {}, Age: {}", my_struct.name, my_struct.age);
}
In this example:
new
function takes name
and age
as arguments, because they are public fields.secret
field is initialized to Default::default()
since it's private and not included in the function arguments.use impl_new_derive::ImplNew;
#[derive(ImplNew, Default)]
struct MyStruct<T> {
pub value: T,
count: usize, // This field is private
}
fn main() {
let my_struct = MyStruct::new(42);
println!("Value: {}", my_struct.value);
}
In this generic struct example:
new
function takes value
as an argument.count
field, being private, is automatically initialized with Default::default()
.When you annotate a struct with #[derive(ImplNew)]
, the macro performs the following actions:
new
function.Default::default()
.impl
block.struct
with named members).Default
, the macro will fail to compile.Feel free to open issues or pull requests if you have any suggestions or improvements.
This project is licensed under the MIT License.