选项<接收器>在上一个循环迭代中移动 [英] Option<Receiver> Moved in Previous Loop Iteration
问题描述
我正在生成一个线程来做一些工作.有时我希望这个线程在工作完成后死亡,其他时候我希望它等待更多的工作去做.为此,我传入了一个 Option
.如果 Option
是 None
线程应该死亡,否则它应该等待接收更多工作.
I'm spawning a thread that does some work. Sometimes I want this thread to die after the work is finished, other times I want it to wait for more work to do. To do this I pass in an Option<Receiver<T>>
. If Option<Receiver<T>>
is None
the thread should die, else it should wait to receive more work.
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
中,一切都很好.
However if the Receiver
is not enclosed in an Option
everything is fine.
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
,使其不可用待会儿.
When you write if let Some(r) = rx
, you consume rx
, making it unavailable for later.
您可以使用 as_ref()
来获取对内部对象的引用,而使 rx
可用:
You can use as_ref()
to get a reference to the inner object instead, leaving rx
usable:
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
}
}
});
}
(链接到操场)
这篇关于选项<接收器>在上一个循环迭代中移动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!