#decorator #procedural #derive #macro #setter #proc-macro

macro decorators

A macro for generating decorator methods

2 releases

0.1.4 May 22, 2022
0.1.3 May 22, 2022
0.1.2 Jun 24, 2021
0.1.1 Jun 24, 2021
0.1.0 Jun 24, 2021

#16 in #decorator


Used in pork

MIT/Apache

8KB
78 lines

A Procedural Macro for Decorators

The Decorator macro generates a decorator method for each field, which is marked with #[dec] in front. Additionaly a field of type Option<T> can be marked with #[opt_dec]. This generates a decorator method that will set the value to Some(t).

Example

#[derive(Decorator)]
struct Widget {
    #[dec]
    width: u32,
    #[dec]
    height: u32,

    #[opt_dec]
    background_color: Option<RGBA>,
}

Generates into:

struct Widget {
    width: u32,
    height: u32,
    background_color: Option<RGBA>,
}
impl Widget {
    pub fn width(self, width: u32) -> Self {
        Self {
            width,
            ..self
        }
    }
    pub fn height(self, height: u32) -> Self {
        Self {
            height,
            ..self
        }
    }
    pub fn background_color(self, background_color: RGBA) -> Self {
        Self {
            background_color: Some(background_color),
            ..self
        }
    }
}

Which can be used like:

let w = some_widget.width(10).height(20);
assert_eq!(w, Widget {width: 10, height: 20, background_color: None});

Dependencies

~1.5MB
~33K SLoC