首页 > 解决方案 > 在 Stream 中使用异步 fn 时的生命周期冲突

问题描述

我正在尝试Conn::event在异步循环中使用以下异步 fn,但出现以下错误:

错误[E0495]:由于需求冲突,无法推断 autoref 的适当生命周期

从我对这个问题的有限理解来看,我认为这是在抱怨,因为对 self 的引用与脱糖Future类型有关,它需要'static一生,而try_for_each需要更少的东西?我在这里不合群!

我怎样才能将此代码重构为...嗯...工作?

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=6d5222afe9cc7d9bbe41f7ac0a29d72a

use futures::{Sink, SinkExt, TryFutureExt, TryStreamExt};
use std::marker::Unpin;
use tokio::io::{self, AsyncBufReadExt};

pub struct Conn<S> {
    sink: S,
}

impl<S> Conn<S>
where
    S: Sink<String>,
    S: Unpin,
{
    pub async fn event(&mut self, data: String) -> Result<(), ()> {
        self.sink.send(data).await.map_err(|_| ())
    }

    pub async fn run(self) -> Result<(), ()> {
        io::BufReader::new(io::stdin())
            .lines()
            .map_err(|_| ())
            .try_for_each(|event| self.event(event))
            .await
    }
}

fn main() {}

标签: rustasync-await

解决方案


推荐阅读