[英]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.