首页 > 解决方案 > 为什么当我将值移动到衍生的 Tokio 任务中时,Rust 的生命周期很重要?

问题描述

我正在尝试创建一个结构来管理 Tokio 任务,其中一个tokio::sync::mpsc::Sender向任务发送输入,一个tokio::sync::mpsc::Receiver从任务接收输出,以及一个我可以在最后加入的句柄。

use tokio::sync::mpsc;
use tokio::task::JoinHandle;

// A type that implements BlockFunctionality consumes instances of T and
// produces either Ok(Some(U)) if an output is ready, Ok(None) if an output
// is not ready, or an Err(_) if the operation fails
pub trait BlockFunctionality<T, U> {
    fn apply(&mut self, input: T) -> Result<Option<U>, &'static str>;
}

pub struct Block<T, U> {
    pub tx_input: mpsc::Sender<T>,
    pub rx_output: mpsc::Receiver<U>,
    pub handle: JoinHandle<Result<(), &'static str>>,
}

impl<T: Send, U: Send> Block<T, U> {
    pub fn from<B: BlockFunctionality<T, U> + Send>(b: B) -> Self {
        let (tx_input, mut rx_input) = mpsc::channel(10);
        let (mut tx_output, rx_output) = mpsc::channel(10);

        let handle: JoinHandle<Result<(), &'static str>> = tokio::spawn(async move {
            let mut owned_b = b;

            while let Some(t) = rx_input.recv().await {
                match owned_b.apply(t)? {
                    Some(u) => tx_output
                        .send(u)
                        .await
                        .map_err(|_| "Unable to send output")?,
                    None => (),
                }
            }

            Ok(())
        });

        Block {
            tx_input,
            rx_output,
            handle,
        }
    }
}

当我尝试编译它时,我得到了这个错误,B而其他两个类型参数也出现了类似的错误:

   |
22 |     pub fn from<B: BlockFunctionality<T, U> + Send>(b:B) -> Self {
   |                 -- help: consider adding an explicit lifetime bound...: `B: 'static +`
...
27 |         let handle:JoinHandle<Result<(), &'static str>> = tokio::spawn(async move {
   |                                                           ^^^^^^^^^^^^ ...so that the type `impl std::future::Future` will meet its required lifetime bounds

我很难理解生命周期的问题所在。我理解它的方式,生命周期问题通常来自寿命不够长的引用,但我正在移动值,而不是使用引用。我将b, rx_input, and移动tx_output到闭包中,并将tx_input, rx_output, and保留handle在调用范围内。有谁知道在这种情况下如何满足编译器?

标签: rustownershiprust-tokiolifetime-scoping

解决方案


这些可能是引用或包含引用。引用类型是有效类型:B可能是&'a str. 或者B可以是SomeType<'a>具有生命周期参数的类型,它本身包含一个&'a str.

这么说B: 'static意味着所有生命周期参数的寿命都B超过了'staticref)。例如,拥有自己的数据并因此没有生命周期参数(例如String)的类型满足此界限。但&'static str也满足了界限。

因为tokio::spawn创建了一些生命周期不是静态范围的东西,所以它需要一个'static参数

所以为了满足编译器,添加'static边界:

impl<T: 'static + Send, U: 'static + Send> Block<T, U> {
    pub fn from<B: 'static + BlockFunctionality<T, U> + Send>(b:B) -> Self {

推荐阅读