我知道,你说你想要的东西更优雅和不枚举,但我认为枚举的解决方案是相当优雅。所以这里有一个尝试:
use std::fs;
use std::io::{self, Read, Seek, SeekFrom};
enum Input {
File(fs::File),
Stdin(io::Stdin),
}
impl Read for Input {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match *self {
Input::File(ref mut file) => file.read(buf),
Input::Stdin(ref mut stdin) => stdin.read(buf),
}
}
}
impl Seek for Input {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
match *self {
Input::File(ref mut file) => file.seek(pos),
Input::Stdin(_) => {
Err(io::Error::new(
io::ErrorKind::Other,
"not supported by stdin-input",
))
},
}
}
}
把这样的代码放在你的一些子模块中,不要再担心它了。您可以使用Input
类型的对象,就像您使用File
一样:无论如何,您必须处理查找错误,因此处理无法通过stdin查找应该非常容易。举例:
let arg = std::env::args().nth(1).unwrap();
let mut input = if arg == "--" {
Input::Stdin(io::stdin())
} else {
Input::File(fs::File::open(&arg).expect("I should handle that.."))
};
let mut v = Vec::new();
let _idc = input.read_to_end(&mut v);
match input.seek(SeekFrom::End(0)) {
Err(_) => println!("oh noes :("),
Ok(bytes) => println!("yeah, input is {} long", bytes),
}
你需要什么操作来“查找”输入?如果你真的需要一个任意的“seek”,唯一的希望就是将整个stdin读入一个'Cursor>'。 –
kennytm
你显然不需要**来寻求你是否可以处理来自stdin的阅读。 – Shepmaster