我要产生一个可以做一些工作的线程。有时我希望该线程在工作完成后死亡,而其他时候我希望它等待更多的工作。为此,我通过Option<Receiver<T>>
。如果Option<Receiver<T>>
是None
,则线程应该死亡,否则应该等待收到更多工作。
fn foo(rx: Option<Receiver<usize>>) {
thread::spawn(move || {
loop {
do_some_work();
if let Some(r) = rx {
match r.recv() {
Ok(x) => {}
Err(_) => panic!("Oh no!"),
}
} else {
break; //Die
}
}
});
}
(链接到操场)
编译器说:
error[E0382]: use of moved value
--> src/lib.rs:10:25
|
10 | if let Some(r) = rx {
| ^ value moved here, in previous iteration of loop
|
= note: move occurs because value has type `std::sync::mpsc::Receiver<usize>`, which does not implement the `Copy` trait
但是,如果Receiver
未封闭在Option
中,则一切都很好。
fn foo(rx: Receiver<usize>) {
thread::spawn(move || {
loop {
do_some_work();
match rx.recv() {
Ok(x) => {}
Err(_) => panic!("Oh no!"),
}
}
});
}
编写 if let Some(r) = rx
时,您会消耗 rx
,使其不可用。
您可以使用as_ref()
来获取对内对象的引用,而rx
可用:
fn foo(rx: Option<Receiver<usize>>) {
thread::spawn(move || {
loop {
do_some_work();
if let Some(r) = rx.as_ref() {
match r.recv() {
Ok(x) => {}
Err(_) => panic!("Oh no!"),
}
} else {
break; //Die
}
}
});
}
(链接到游乐场)