简体   繁体   English

取得 and_then 中 rust 未来的闭包参数的所有权

[英]Take ownership of closure argument for rust future in and_then

I am trying to read all content from a file into a vector using the async rust api:我正在尝试使用异步 rust api 将文件中的所有内容读入向量:

    let mut content : Vec<u8> = vec![];
    let f = tokio::fs::File::open("myfilecontent")
        .and_then(|mut myfile| {
            myfile.read_buf(&mut content)
        });
    f.await;

But I keep getting this error: error[E0515]: cannot return value referencing function parameter `myfile`但我不断收到此错误: error[E0515]: cannot return value referencing function parameter `myfile`

Which sounds reasonable, because the future returned by the closure must keep a reference to the file, but as this closure is the only user of the file it could take ownership.这听起来很合理,因为闭包返回的未来必须保留对文件的引用,但由于这个闭包是文件的唯一用户,它可以拥有所有权。 How can I convince rust to do the right thing?如何说服 rust 做正确的事?

You can use an async move block like so:您可以像这样使用async move块:

use futures::TryFutureExt;
use tokio::io::AsyncReadExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut content: Vec<u8> = vec![];

    let f = tokio::fs::File::open("myfilecontent").and_then(
        |mut myfile| async move { myfile.read_buf(&mut content).await },
    );

    f.await?;

    Ok(())
}

or skip and_then and go straight for .await :或直接跳过and_then和 go 为.await

use tokio::io::AsyncReadExt;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut content: Vec<u8> = vec![];

    let mut myfile = tokio::fs::File::open("myfilecontent").await?;
    myfile.read_buf(&mut content).await?;

    Ok(())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM