如何将通用类型参数移动到异步移动块?

hel*_*ios 0 generics lifetime rust async-await

我正在尝试用 Rust 写一些东西(我喜欢它,但还没有太多经验),但发现了一个我不知道如何解决的障碍。

我的目的是生成一个异步任务,传递初始状态作为参数。异步任务将获取该值(它可以保留它的所有权)并进一步使用它。问题是初始值需要是通用的。我收到一个错误,抱怨 的生命周期StateT ,并且我无法让编译器知道我想将其移动/复制到异步块。

async fn start<StateT>(initial_value: StateT) -> impl futures::Future
where
    StateT: Send,
{
    tokio::spawn(async move {
        process(initial_value);
    })
}
Run Code Online (Sandbox Code Playgroud)

我尝试制作StateT: Copy + Send + Sync等,但它不喜欢它。只能'static工作,但我想这是不对的(这不是我要传递的常量,而是一些任意的结构)。

错误信息是:

error[E0310]: the parameter type `StateT` may not live long enough
 --> src/workflow2.rs:7:5
  |
7 | /     tokio::spawn(async move {
8 | |         process(initial_value);
9 | |     })
  | |______^ ...so that the type `StateT` will meet its required lifetime bounds
  |
help: consider adding an explicit lifetime bound...
  |
5 |     StateT: Send + 'static,
  |                  +++++++++
Run Code Online (Sandbox Code Playgroud)

如果我尝试传递 ani32或 aString而不是泛型,它就可以正常工作。所以我想我缺少一些可以StateT提供所缺少内容的特征。

Jmb*_*Jmb 6

只有 'static 有效,但我想这是不对的(这不是我要传递的常量,而是一些任意结构)。

这是常见的 Rust 生命周期误解#2T: 'static并不意味着T整个程序都存在生命周期,更不用说它T是一个常量。它只意味着它T是一个完全独立的类型并且它不借用任何其他数据。所以StateT: 'static在这里做正确的事情是:

async fn start<StateT>(initial_value: StateT) -> impl futures::Future
where
    StateT: Send + 'static,
{
    tokio::spawn(async move {
        process(initial_value);
    })
}
Run Code Online (Sandbox Code Playgroud)

  • 并不是说它不包含任何引用,而是它不包含任何非静态引用。 (2认同)