首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从“文件”推广到“阅读”?

如何从“文件”推广到“阅读”?
EN

Stack Overflow用户
提问于 2021-01-10 20:08:03
回答 1查看 107关注 0票数 1

我有一些读取文件的工作代码,但我需要将其概括为从简单磁盘文件以外的其他来源提取数据。

为了替换File

  • If,
  1. 是正确的泛化,因此,如何在下面的示例代码中修复example2?实际上,它在注释行的编译错误dyn async_std::io::Read cannot be unpinned中失败。如果没有,我应该从example2

返回哪些类型,并且是否需要在get_read中进行相应的更改?

代码语言:javascript
复制
//! [dependencies]
//! tokio = { version = "1.0.1", features = ["full"] }
//! async-std = "1.8.0"
//! anyhow = "1.0.32"

use async_std::io::prelude::*;
use async_std::fs::File;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    example1().await?;
    example2().await?;
    Ok(())
}

// Example of consuming `File` ... works great!
async fn example1() -> Result<()> {
    let mut file = get_file().await?;
    let mut contents = String::new();
    let _ = file.read_to_string(&mut contents).await?;
    println!("read {} characters", contents.len());
    Ok(())
}

// Example of consuming `Read` ... does not compile?
async fn example2() -> Result<()> {
    let mut read = get_read().await?;
    let mut contents = String::new();
    // ERROR:  `dyn async_std::io::Read` cannot be unpinned
    let _ = read.read_to_string(&mut contents).await?;
    println!("read {} characters", contents.len());
    Ok(())
}

async fn get_read() -> Result<Box<dyn Read>> {
    let file = get_file().await?;
    Ok(Box::new(file))
}

async fn get_file() -> Result<File> {
    let file = File::open("/etc/hosts").await?;
    Ok(file)
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-11 02:29:28

你需要钉:

代码语言:javascript
复制
async fn get_read() -> Result<Pin<Box<dyn Read>>> {
    let file = get_file().await?;
    Ok(Box::pin(file))
}

Box<File> (没有Pin)工作是因为文件实现了Unpin。Box<dyn Read + Unpin>也能工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65657959

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档