Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to create a macro to implement builder pattern methods?

Tags:

rust

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);
}     
like image 304
Victor Polevoy Avatar asked Mar 11 '23 19:03

Victor Polevoy


2 Answers

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.

like image 121
Victor Polevoy Avatar answered May 10 '23 13:05

Victor Polevoy


To complement the already accepted answer, since it is 4 years old by now, you should check out the crate rust-derive-builder. It uses procedural macros to automatically implement the builder pattern for any struct.

like image 44
LeoVen Avatar answered May 10 '23 11:05

LeoVen