Common Code for Files and Pipes in Rust

To read a file in Rust, the following code is easy enough to figure:

Code
fn open(file_name: &str) -> Result<(), Error> {
let input = File::open(file_name)?;
let mut reader = io::BufReader::new(input);

What if you want to read from standard input when file is not given? In many other languages you might solve this using interface. However, in Rust we haven't got interface support. What we do have are traits.

Code
fn parse(file_name: Option<&str>) -> Result<(), Error> {
let input = match file_name {
Some(file_name) => Box::new(File::open(file_name)?) as Box<Read>,
None => Box::new(io::stdin()) as Box<Read>,
};
let mut reader = io::BufReader::new(input);

As you can see, it reads almost exactly like an interface would, the only curiosity being explicit boxing you have to do.

To see the code in context, you can check IniEd and it's implementation.

Leave a Reply

Your email address will not be published. Required fields are marked *