如何从Rust中的File或stdin执行多态IO?

nee*_*tza 13 io polymorphism rust

我正在尝试实现一个"多态" Input枚举,它隐藏我们是从文件还是从stdin读取.更具体地说,我正在尝试构建一个枚举,它将有一个lines方法,该方法将"委托"该调用转换为File包含在a BufReader或a中StdInLock(两者都具有该lines()方法).

这是枚举:

enum Input<'a> {
    Console(std::io::StdinLock<'a>),
    File(std::io::BufReader<std::fs::File>)
}
Run Code Online (Sandbox Code Playgroud)

我有三种方法:

  • from_arg 通过检查是否提供了参数(文件名)来判断我们是从文件还是从stdin读取,
  • file用a包装文件BufReader,
  • console 用于锁定标准输入.

实施:

impl<'a> Input<'a> {
    fn console() -> Input<'a> {
        Input::Console(io::stdin().lock())
    }

    fn file(path: String) -> io::Result<Input<'a>> {
        match File::open(path) {
            Ok(file) => Ok(Input::File(std::io::BufReader::new(file))),
            Err(_) => panic!("kita"),
        }
    }

    fn from_arg(arg: Option<String>) -> io::Result<Input<'a>> {
        Ok(match arg {
            None => Input::console(),
            Some(path) => try!(Input::file(path)),
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,我必须实现这两个BufReadRead特征才能发挥作用.这是我的尝试:

impl<'a> io::Read for Input<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        match *self {
            Input::Console(ref mut c) => c.read(buf),
            Input::File(ref mut f) => f.read(buf),
        }
    }
}

impl<'a> io::BufRead for Input<'a> {
    fn lines(self) -> Lines<Self> {
        match self {
            Input::Console(ref c) => c.lines(),
            Input::File(ref f) => f.lines(),
        }
    }

    fn consume(&mut self, amt: usize) {
        match *self {
            Input::Console(ref mut c) => c.consume(amt),
            Input::File(ref mut f) => f.consume(amt),
        }
    }

    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        match *self {
            Input::Console(ref mut c) => c.fill_buf(),
            Input::File(ref mut f) => f.fill_buf(),
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

最后,调用:

fn load_input<'a>() -> io::Result<Input<'a>> {
    Ok(try!(Input::from_arg(env::args().skip(1).next())))
}

fn main() {
    let mut input = match load_input() {
        Ok(input) => input,
        Err(error) => panic!("Failed: {}", error),
    };

    for line in input.lines() { /* do stuff */ }
}
Run Code Online (Sandbox Code Playgroud)

完整的例子在操场上

编译器告诉我,我的模式匹配错误,我有mismatched types:

error[E0308]: match arms have incompatible types
  --> src/main.rs:41:9
   |
41 | /         match self {
42 | |             Input::Console(ref c) => c.lines(),
   | |                                      --------- match arm with an incompatible type
43 | |             Input::File(ref f) => f.lines(),
44 | |         }
   | |_________^ expected enum `Input`, found struct `std::io::StdinLock`
   |
   = note: expected type `std::io::Lines<Input<'a>>`
              found type `std::io::Lines<std::io::StdinLock<'_>>`
Run Code Online (Sandbox Code Playgroud)

我试图满足它:

match self {
    Input::Console(std::io::StdinLock(ref c)) => c.lines(),
    Input::File(std::io::BufReader(ref f)) => f.lines(),
}
Run Code Online (Sandbox Code Playgroud)

......但这也不起作用.

看来,我真的超出了我的深度.

A.B*_*.B. 15

这是最简单的解决方案,但会借用和锁定Stdin.

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

struct Input<'a> {
    source: Box<BufRead + 'a>,
}

impl<'a> Input<'a> {
    fn console(stdin: &'a io::Stdin) -> Input<'a> {
        Input {
            source: Box::new(stdin.lock()),
        }
    }

    fn file(path: &str) -> io::Result<Input<'a>> {
        File::open(path).map(|file| Input {
            source: Box::new(io::BufReader::new(file)),
        })
    }
}

impl<'a> Read for Input<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.source.read(buf)
    }
}

impl<'a> BufRead for Input<'a> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        self.source.fill_buf()
    }

    fn consume(&mut self, amt: usize) {
        self.source.consume(amt);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于默认的特征方法,Read并且BufRead完全实现了Input.所以,你可以叫linesInput.

let input = Input::file("foo.txt").unwrap();
for line in input.lines() {
    println!("input line: {:?}", line);
}
Run Code Online (Sandbox Code Playgroud)


Yer*_*rke 13

@AB的答案是正确的,但它试图符合OP的原始程序结构.对于偶然发现这个问题的新手,我希望有一个更具可读性的选择(就像我一样).

use std::env;
use std::fs;
use std::io::{self, BufReader, BufRead};

fn main() {
    let input = env::args().nth(1);
    let reader: Box<BufRead> = match input {
        None => Box::new(BufReader::new(io::stdin())),
        Some(filename) => Box::new(BufReader::new(fs::File::open(filename).unwrap()))
    };
    for line in reader.lines() {
        println!("{:?}", line);
    }
}
Run Code Online (Sandbox Code Playgroud)

请参阅我从中借用代码的reddit中的讨论.

  • 您甚至应该能够在这里利用 [On-Stack Dynamic Dispatch](https://rust-unofficial.github.io/patterns/idioms/on-stack-dyn-dispatch.html),但这可能会直接进行违背你的可读性目标。 (2认同)