在结构中使用特征作为类型参数时,借用检查器出现问题:
trait Trait {}
struct FooBar;
impl Trait for FooBar{}
struct Observer<Arg> {
action: Box<Fn(Arg) + Send>,
// Other fields
}
impl <Arg> Observer<Arg> {
fn new(action: Box<Fn(Arg) + Send>) -> Observer<Arg> {
Observer{action: action}
}
fn execute(&self, arg: Arg) {
(*self.action)(arg);
}
}
fn test() {
let mut foobar = FooBar;
{
let mut observer = Observer::new(Box::new(|&: param: &mut Trait| {
// do something with param here
}));
observer.execute(&mut foobar); // First borrow passes ...
observer.execute(&mut foobar); // This fails as "foobar" is already borrowed
} // The previous borrow ends here (lifetime of "observer")
}
输出是:
error: cannot borrow `foobar` as mutable more than once at a time
observer.execute(&mut foobar); // This fails as "foobar" is already borrowed
^~~~~~
note: previous borrow of `foobar` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `foobar` until the borrow ends
observer.execute(&mut foobar); // First borrow passes ...
^~~~~~
note: previous borrow ends here
{
...
} // The previous borrow ends here (lifetime of "observer")
^
然而,以下示例有效:
trait Trait {}
struct FooBar;
impl Trait for FooBar{}
struct Observer {
action: Box<Fn(&mut Trait) + Send>,
// Other fields
}
impl Observer {
fn new(action: Box<Fn(&mut Trait) + Send>) -> Observer {
Observer{action: action}
}
fn execute(&self, arg: &mut Trait) {
(*self.action)(arg);
}
}
fn test() {
let mut foobar = FooBar;
{
let mut observer = Observer::new(Box::new(|&: param: &mut Trait| {
// do something with param here
}));
observer.execute(&mut foobar);
observer.execute(&mut foobar);
}
}
这对我来说真的很奇怪,因为第二个示例只是第一个示例的实例化,我可能(痛苦地)用宏实现同样的事情。
我想这很棘手,因为我需要知道闭包所采用的参数类型,但我不需要存储这个引用......
这是借用检查器中的错误吗?还是我做错了什么?
rustc 1.0.0-nightly (44a287e6e 2015-01-08 17:03:40 -0800)
编辑 1:精确用例
编辑 2:正如下面的答案所解释的,问题是借用检查器强制生命周期Observer<&mut Type>
与&mut Type
对实际结构做同样的事情)。
所以在我的情况下,我可以通过Observer<Arg>
这样定义来解决:
struct Observer<Arg> {
action: Box<Fn(&mut Arg) + Send>,
}
所以类型参数 Arg 本身不是一个引用,但这使得代码不那么通用。有人有更好的解决方案吗?