【问题标题】:tokio::spawn captured with 'static lifetimetokio::spawn 用“静态生命周期”捕获
【发布时间】:2020-06-14 06:36:07
【问题描述】:

我是新手,尝试理解以下错误:

use rybw_config::ListenerConfig;
use tokio::prelude::*;
use tokio::task::JoinHandle;
pub mod tcp;
use tcp::TCPListener;

pub struct Listener {
    config: ListenerConfig,
    tcp: Vec<tcp::TCPListener>,
}

impl Listener {
    pub fn new(config: ListenerConfig) -> Listener {
        let tcp: Vec<TCPListener> = config
            .tcp
            .clone()
            .unwrap()
            .iter()
            .map(|x| TCPListener::new((*x).clone()))
            .collect();

        Listener {
            tcp: tcp,
            config: config.clone(),
        }
    }

    pub async fn run(&self) {
        let handles: Vec<JoinHandle<()>> = self.tcp.iter().map(|i| {
            tokio::spawn(async {
                i.run().await
            })
        }).collect();
        futures::future::join_all(handles);
    }

尝试通过 tokio 运行多 tcp 侦听器,但收到如下错误:

error: cannot infer an appropriate lifetime
  --> rybw-listener/src/lib.rs:28:22
   |
28 |     pub async fn run(&self) {
   |                      ^^^^^
   |                      |
   |                      data with this lifetime...
   |                      ...is captured here...
29 |         let handles: Vec<JoinHandle<()>> = self.tcp.iter().map(|i| {
30 |             tokio::spawn(async {
   |             ------------ ...and required to be `'static` by this

类似问题Confused about variable lifetime in tokio::spawn(async move

【问题讨论】:

    标签: rust rust-tokio tokio


    【解决方案1】:

    自己解决。

    rust 闭包捕获结构,而不是单个字段。所以我们用 std::sync::Arc 包装 TCPListener 并克隆它然后用于 spawn async {}

    【讨论】:

    • 我遇到了同样的问题,我无法解决它,你能解释一下你的解决方案吗?
    猜你喜欢
    • 2020-06-26
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多