【发布时间】:2017-04-26 20:57:38
【问题描述】:
我正在使用编译器插件构建一个惰性表达式评估器like Python's。
我想打印如下日志:
assert ( left == vec![1, 2, 3, 4] )
assert ( vec![1, 2, 3, 4] == vec![1, 2, 3, 4] );
并尝试过:
// crate rt
pub struct Expr<T, F: FnMut() -> T> {
// I noticed that this must be changed to fn with format!() call, to
// support updating child.
src: &'static str, // holds value
}
pub trait EvalTo: Display {
/// Type of expression
type Type;
/// Returns Some(val) when done
/// Accepts &mut self as it might be called many time.
fn eval_one_level(&mut self) -> Some<T>;
}
impl<T, F> EvalTo for Expr<T, F> {
type Type = T;
}
/// Prints source before evaluation, (it must be changed)
/// and value after evaluation.
impl<T, F> Display for Expr<T, F> {}
使用编译器插件在编译时创建它们。但是当我这样做时
let left = vec![1, 2, 3, 4];
lazy_expr!(left == vec![1, 2, 3, 4]);
它扩展到
::rt::binary({
::rt::Expr::wrap(::rt::Source{ expr: "left" }, || Some(left))
}, {
::rt::Expr::wrap(::rt::Source{ expr: "vec!(1, 2, 3, 4)" },
|| vec![1, 2, 3, 4])
}).eq()
并且编译器不喜欢它。上面写着cannot move out of captured outer variable in an `FnMut` closure。
所以我不能使用FnMut,但是需要多次调用,并且需要能够修改子表达式。
是否有允许捕获局部变量但可以使用&mut self 多次调用的数据结构?我应该使用FnOnce(&mut Context)吗?
【问题讨论】:
-
请生成minimal reproducible example。不太可能有人会创建一个编译器插件来尝试重现您的错误。理想情况下,制作可以run on the playground 的东西。更好的是,review the 7 other questions with the same error message在询问之前。然后,解释为什么这个问题与那些问题不同。
-
我决定做类似pybites.blogspot.kr/2011/07/… 的事情,因为我不能用泛型表示 ast,这个问题对我来说毫无用处。
-
@Shepmaster 这是关于设计的问题,这些问题是关于使用 FnMut 的。我不是试图将价值转移到关闭。相反,我想做一些事情,比如同时允许 FnOnce 和 FnMut。我发现这可以通过futures-rs
标签: rust lazy-evaluation