选项<接收器>在上一个循环迭代中移动 [英] Option&lt;Receiver&gt; Moved in Previous Loop Iteration

查看:58
本文介绍了选项<接收器>在上一个循环迭代中移动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在生成一个线程来做一些工作.有时我希望这个线程在工作完成后死亡,其他时候我希望它等待更多的工作去做.为此,我传入了一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆