This derive macro creates a const fn new
associated function receiving as parameters the same fields declared in your struct
.
So this:
... will create this:
ps: Rust Analyzer already generates new
function for you!
https://rust-analyzer.github.io/manual.html#assists-code-actions
ps2: I just found (2023-11-12) another crate that already does that! =) And it's funny that it has the same name, but swapped: derive-new
It's more powerful than this one, because it handles default values, enums
and PhantomData
.
Although this crate creates a const
fn, while derive-new
doesn't.
Using it
https://crates.io/crates/new-derive
cargo add new-derive
`use New;
Output:
24
[src/main.rs:44] s1 = S1 {
array1: [
1,
2,
3,
],
name: "Leandro",
}
[src/main.rs:48] s2 = S2 {
opt1: Some(
"ola",
),
idx: 30,
map1: {
10: 20,
},
}
Country is: Brazil