rust - 为什么当我将值移动到衍生的 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
在调用范围内。有谁知道在这种情况下如何满足编译器?
解决方案
这些值可能是引用或包含引用。引用类型是有效类型:B
可能是&'a str
. 或者B
可以是SomeType<'a>
具有生命周期参数的类型,它本身包含一个&'a str
.
这么说B: 'static
意味着所有生命周期参数的寿命都B
超过了'static
(ref)。例如,拥有自己的数据并因此没有生命周期参数(例如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 {
推荐阅读
- python - 打印文本框中的文本 PYTHON SELENIUM
- libreoffice - 你能打印在 writer 中由 Spell check 生成的波浪线吗?
- django - 我正在尝试使用 heroku 部署 django 应用程序但出现错误?
- javascript - Filter Grid View on Date
- c# - C#方法返回一个对象列表
- html - CSS 没有从子文件夹中导入字体和图像
- javascript - 如何使用按钮清除 Material-ui 搜索输入
- php - Laravel - 获取会话价值的问题
- python - 列表中的组合元素以可能的方式超过 O(n^n)
- php - 如何访问 Laravel Blade 文件中对象内的对象?