你可以将 futures::StreamExt::take_while 与非复制项目一起使用吗?

问题描述 投票:0回答:0

我可以在 SO 上找到的所有示例和 futures::stream::take_while

documentation
在使用适配器时使用
Copy
的项目。但在我的用例中,我流过的项目是非
Copy
。这似乎使
take_while
无法与异步流一起使用 任何时候谓词需要使用[引用]检查中的项目,这基本上总是。

据我所知,它总是会导致生命周期错误,因为未来的返回类型包含生命周期。

use std::pin::Pin;

use futures_util::{Stream, StreamExt};
use tokio_tungstenite::tungstenite::error::Error;
use tokio_tungstenite::tungstenite::protocol::Message;


async fn process_messages(mut read: Pin<&mut impl Stream<Item = Result<Message, Error>>>) {
    read
     .take_while(|x: &Result<Message, tungstenite::Error>| 
         async { x; true } // would compile if removed the `x;`
     );
}

#[tokio::main]
async fn main() {
    let url = url::Url::parse("wss://127.0.0.1:12345").unwrap();

    let (ws_stream, _) = tokio_tungstenite::connect_async(url).await.expect("Failed to connect");

    let (_, read) = ws_stream.split();
    tokio::pin!(read);

    process_messages(read).await;
}

错误:

error: lifetime may not live long enough
  --> src/main.rs:13:63
   |
13 |     read.take_while(|x: &Result<Message, tungstenite::Error>| async { x; true });
   |                         -                                   - ^^^^^^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
   |                         |                                   |
   |                         |                                   return type of closure `[async block@src/main.rs:13:63: 13:80]` contains a lifetime `'2`
   |                         let's call the lifetime of this reference `'1`

error[E0373]: async block may outlive the current function, but it borrows `x`, which is owned by the current function
  --> src/main.rs:13:63
   |
13 |     read.take_while(|x: &Result<Message, tungstenite::Error>| async { x; true });
   |                                                               ^^^^^^^^-^^^^^^^^
   |                                                               |       |
   |                                                               |       `x` is borrowed here
   |                                                               may outlive borrowed value `x`
rust stream lifetime rust-tokio
© www.soinside.com 2019 - 2024. All rights reserved.