如何返回包含在 Result 中的 impl Trait?

Lis*_*one 1 traits rust

我有一个函数可以从文件或网络中读取一些内容,然后返回内容。为简单起见,我们使用以下仅针对文件的内容:

fn test() -> Result<Vec<u8>, Error> {
    let mut buf = Vec::new();
    // Does some things that may error ...
    File::open("test.txt")?.read_to_end(&mut buf)?;
    Ok(buf)
}
Run Code Online (Sandbox Code Playgroud)

是否可以编写此函数,使其返回Read包装在Result其中的特征,以便不需要立即将完整内容读入内存?

She*_*ter 5

如何返回包含在 Result 中的 impl Trait?

通过返回包裹在其中的 impl 特征Result

use std::{
    fs::File,
    io::{self, Read},
};

fn test() -> io::Result<impl Read> {
    let f = File::open("test.txt")?;
    Ok(f)
}
Run Code Online (Sandbox Code Playgroud)

也可以看看: