我是新生的,并且在所有权/借款方面仍然存在一些问题.在这种情况下,我想在枚举中存储一个FnOnce,然后从另一个线程调用它.我尝试了很多不同的变种,但总是卡在某个地方.这是我目前拥有的缩小版本:
#![feature(fnbox)]
use std::sync::{Arc, Mutex};
use std::boxed::{Box, FnBox};
enum Foo<T> {
DoNothing,
CallFunction(Box<FnBox(&T) + Send>)
}
struct FooInMutex<T> {
foo: Arc<Mutex<Foo<T>>>
}
impl<T> FooInMutex<T> {
fn put_fn(&self, f: Box<FnBox(&T)+Send>) {
let mut foo = self.foo.lock().unwrap();
let mut new_foo : Foo<T>;
match *foo {
Foo::DoNothing =>
new_foo = Foo::CallFunction(f),
_ =>
new_foo = Foo::DoNothing
}
*foo = new_foo;
}
fn do_it(&self, t: T) {
let mut foo = self.foo.lock().unwrap();
let mut new_foo : Foo<T>;
match *foo {
Foo::CallFunction(ref mut f) => {
//f(&t)
f.call_box((&t,));
new_foo = Foo::DoNothing;
}
_ =>
panic!("...")
}
*foo = new_foo;
}
}
#[test]
fn it_works() {
let x = FooInMutex { foo: Arch::new(Mutex::new(Foo::DoNothing)) };
x.put_fn(Box::new(|| panic!("foo")));
x.do_it();
}
Run Code Online (Sandbox Code Playgroud)
我使用"rustc 1.4.0-nightly(e35fd7481 2015-08-17)".错误消息:
src/lib.rs:35:17: 35:18 error: cannot move out of borrowed content
src/lib.rs:35 f.call_box((&t,));
^
Run Code Online (Sandbox Code Playgroud)
据我了解,f由互斥锁中的枚举所有,我只通过*foo借用它.但是为了调用f,我需要把它移出去.但是怎么做呢?或者我需要改变什么以使这个例子有效?
std::mem::replace
是你应该在那里使用,像这样:
use std::mem;
…
fn do_it(&self, t: T) {
match mem::replace(self.foo.lock().unwrap(), Foo::DoNothing) {
Foo::CallFunction(f) => {
f.call_box((&t,));
}
_ => panic!("...")
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
367 次 |
最近记录: |