2016-07-02 8 views
2

私は、構造体のために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 
    } 
} 

ことが可能ですルーストに一般化したコードを複製の多くを回避するために、このような方法のためのマクロを作成しますか?私たちは、次のように使用することができます何か:

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

答えて

4

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

それは私が必要とする正確に何を行います。指定してパブリックビルダーメソッドを作成します名前、指定されたメンバーおよびタイプ。

関連する問題