我有一个 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);
}
最佳答案
看完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);
}
它完全满足我的需要:创建一个具有指定名称、指定成员和类型的公共(public)构建器方法。
关于rust - 是否可以创建一个宏来实现构建器模式方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38158167/