A procedural macro to generate a new function for your struct.
Add this to your Cargo.toml
:
toml
[dependencies]
impl_new = "0.1.0"
Or run this command in your workspace:
bash
cargo add impl_new
Is simple, just derive the impl_new::New
proc macro on your struct and it will generate a new
function for you.
```rust
struct Foo { name: String, age: usize, }
// The generated code will look like this:
// impl Foo {
// pub fn new(name: impl Into
fn main() {
let foo = Foo::new("Hello", 42usize); // Will use Into::into
to convert the arguments to the fields types.
asserteq!(foo.name, "Hello".tostring());
assert_eq!(foo.age, 42);
}
```
```rust
struct Foo { #[implnew(name = "username")] name: String, #[implnew(name = "userage")] age: usize, }
// The generated code will look like this:
// impl Foo {
// pub fn new(username: impl Into
fn main() {
let foo = Foo::new("Hello", 42usize); // Will use Into::into
to convert the arguments to the fields types.
asserteq!(foo.name, "Hello".tostring());
assert_eq!(foo.age, 42);
}
```
Note: The
#[impl_new(name = "name")]
attribute is required for unnamed fields.
```rust
struct Foo(#[implnew(name = "name")] String, #[implnew(name = "age")] usize);
// The generated code will look like this:
// impl Foo {
// pub fn new(name: impl Into
fn main() {
let foo = Foo::new("Hello", 42usize); // Will use Into::into
to convert the arguments to the fields types.
asserteq!(foo.0, "Hello".tostring());
assert_eq!(foo.1, 42);
}
```
#[impl_new(name = "name")]
: Use this attribute to change the name of the argument in the generated new
function.This project is licensed under the MIT license.