是否可以创建一个宏来实现构建器模式方法? [英] Is it possible to create a macro to implement builder pattern methods?
本文介绍了是否可以创建一个宏来实现构建器模式方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我为我的结构实现了一个构建器模式:
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
}
}
是否可以在 Rust 中为这样的方法创建一个宏来泛化并避免大量重复代码?我们可以使用以下内容:
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);
}
推荐答案
阅读文档后,我想出了这个代码:
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.
这篇关于是否可以创建一个宏来实现构建器模式方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文