Is it possible to create a macro to implement buil

2019-07-20 06:47发布

问题:

I have a builder pattern implemented for my struct:

pub struct Struct {
    pub grand_finals_modifier: bool,
}
impl Struct { 
    pub fn new() -> Struct {
        Struct {
            grand_finals_modifier: false,
        }
    }

    pub fn grand_finals_modifier<'a>(&'a mut self, name: bool) -> &'a mut Struct {
        self.grand_finals_modifier = grand_finals_modifier;
        self
    }
}

Is it possible in Rust to make a macro for methods like this to generalize and avoid a lot of duplicating code? Something that we can use as the following:

impl Struct {
    builder_field!(hello, bool);
}     

回答1:

After reading the documentation, I've come up with this code:

macro_rules! builder_field {
    ($field:ident, $field_type:ty) => {
        pub fn $field<'a>(&'a mut self,
                          $field: $field_type) -> &'a mut Self {
            self.$field = $field;
            self
        }
    };
}

struct Struct {
    pub hello: bool,
}
impl Struct {
    builder_field!(hello, bool);
}

fn main() {
    let mut s = Struct {
        hello: false,
    };
    s.hello(true);
    println!("Struct hello is: {}", s.hello);
}

It does exactly what I need: creates a public builder method with specified name, specified member and type.



标签: rust