【问题标题】:Is it possible to create a macro to implement builder pattern methods?是否可以创建一个宏来实现构建器模式方法?
【发布时间】:2020-07-31 03:19:50
【问题描述】:

我为我的结构实现了builder pattern

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
    }
}

是否可以在 Rust 中为这样的方法创建一个宏来泛化并避免大量重复代码?我们可以使用如下:

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

【问题讨论】:

    标签: rust


    【解决方案1】:

    阅读the documentation后,我想出了这段代码:

    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);
    }
    

    这正是我所需要的:创建一个具有指定名称、指定成员和类型的公共构建器方法。

    【讨论】:

      【解决方案2】:

      为了补充已经接受的答案,因为它现在已经 4 岁了,你应该检查一下箱子 rust-derive-builder。它使用过程宏自动为任何结构实现构建器模式。

      【讨论】:

        猜你喜欢
        • 2018-01-21
        • 1970-01-01
        • 2013-12-03
        • 2015-04-12
        • 1970-01-01
        • 2011-02-27
        • 2017-06-26
        • 1970-01-01
        • 2018-07-23
        相关资源
        最近更新 更多