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

匿名 (未验证) 提交于 2019-12-03 01:00:01

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!