在 and_then 中获得 rust 未来的闭包论证的所有权
Take ownership of closure argument for rust future in and_then
我正在尝试使用异步 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;
但我不断收到此错误:
error[E0515]: cannot return value referencing function parameter `myfile`
这听起来很合理,因为闭包返回的 future 必须保留对该文件的引用,但由于此闭包是该文件的唯一用户,它可以获得所有权。我怎样才能说服 Rust 做正确的事?
您可以像这样使用 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(())
}
或跳过and_then
直接进入.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(())
}
我正在尝试使用异步 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;
但我不断收到此错误:
error[E0515]: cannot return value referencing function parameter `myfile`
这听起来很合理,因为闭包返回的 future 必须保留对该文件的引用,但由于此闭包是该文件的唯一用户,它可以获得所有权。我怎样才能说服 Rust 做正确的事?
您可以像这样使用 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(())
}
或跳过and_then
直接进入.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(())
}