#macro-derive #constructor #macro #struct #derive #new

macro build lilys-new-macro

Macro for generating a 'new' constructor function

2 releases

new 0.1.1 Mar 15, 2025
0.1.0 Mar 11, 2025

#359 in Build Utils

Download history 88/week @ 2025-03-09

88 downloads per month

MIT license

10KB
128 lines

new-macro

This is a macro to automate creating a 'new' function for structs

Crates.io Version Run tests uwu

Examples

Here is a basic sample of the macro in action!

Source Code:

use new_macro::New;
#[derive(New)]
struct Test {
    a: i32,
    #[default(a * 2)]
    b: i32,
}

Generated Code:

struct Test {
    a: i32,
    b: i32,
}

impl Test {
    pub fn new(a: i32) -> Self {
      Self {
        a,
        b: a * 2,
      }
    }
}

lib.rs:

Macro to generate constructor functions

Adds a derive macro New that generates a 'new' function for constructing structs. Also, allows you to control which variables are defaulted and which are required through the sub-attribute default. The default sub-attribute takes an expression as an argument and uses that to calculate the member variable's value on construction.

Panics

When the macro panics, you will see a compile error. It might be vague while I make good compile errors and iron out bugs, but I will work to improve error outputs.

Examples

Here is a basic sample of the macro in action!

Source Code:

use new_macro::New;

#[derive(New)]
struct Test {
    a: i32,
    #[default(a * 2)]
    b: i32,
}

Generated Code:

struct Test {
    a: i32,
    b: i32,
}

impl Test {
    pub fn new(a: i32) -> Self {
      Self {
        a,
        b: a * 2,
      }
    }
}

Dependencies

~205–640KB
~15K SLoC