1

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

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

类似的问题对 tokio::spawn(async move) 中的变量生命周期感到困惑

4

1 回答 1

3

自己解决了。

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

于 2020-06-14T12:49:58.360 回答