是否可以创建一个宏来实现构建器模式方法?

Vic*_*voy 3 rust

我为我的结构实现了一个构建器模式

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
    }
}
Run Code Online (Sandbox Code Playgroud)

在 Rust 中是否有可能为这样的方法创建一个宏来概括并避免大量重复代码?我们可以使用以下内容:

impl Struct {
    builder_field!(hello, bool);
}     
Run Code Online (Sandbox Code Playgroud)

Vic*_*voy 5

阅读文档后,我想出了这个代码:

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);
}
Run Code Online (Sandbox Code Playgroud)

它完全符合我的需要:创建一个具有指定名称、指定成员和类型的公共构建器方法。