我试图将成员函数的主体作为宏参数传递。是否可以更改下面的代码以使其有效?
macro_rules! iterator{
($ty:ty, $ident:ident; $($state_ident:ident: $state_ty:ty), *; $next:block) => (
struct $ident { // ^ the parameter
$($state_ident: $state_ty), *
}
impl Iterator for $ident {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
$next // <- cannot refer to 'self' parameter in this block
}
}
);
}
iterator!(i32, TestIterator; index: i32; {
let value = Some(self.index);
self.index += 1;
value
});
编译错误:
error[E0424]: expected value, found module `self`
--> src/main.rs:18:22
|
18 | let value = Some(self.index);
| ^^^^ `self` value is only available in methods with `self` parameter
error[E0424]: expected value, found module `self`
--> src/main.rs:19:5
|
19 | self.index += 1;
| ^^^^ `self` value is only available in methods with `self` parameter
答案 0 :(得分:4)
一种解决方案是接受闭包而不是块:
macro_rules! iterator{
($ty:ty, $ident:ident; $($state_ident:ident: $state_ty:ty),*; $next:expr) => (
struct $ident {
$($state_ident: $state_ty), *
}
impl Iterator for $ident {
type Item = $ty;
fn next(&mut self) -> Option<$ty> {
$next(self)
}
}
);
}
iterator!(i32, TestIterator; index: i32; |me: &mut TestIterator| {
let value = Some(me.index);
me.index += 1;
value
});
fn main() {}
这需要明确地将self
传递给闭包。您不能在闭包中使用标识符self
,因为self
仅允许在函数的参数列表中声明。
您还需要指定闭包参数的类型,这是闭包的限制,它被定义为变量并在以后使用,而不是立即使用。