How do I overcome match arms with incompatible types for structs implementing same trait?

The problem is that stdin() returns an object of type Stdio and File::open(...).unwrap() returns an object of type File. In Rust, all arms of a match have to return values of the same type.

In this case you probably wanted to return a common Read object. Unfortunately Read is a trait so you cannot pass it by value. The easiest alternative is to resort to heap allocation:

use std::{env, io};
use std::io::prelude::*;
use std::fs::File;

fn main() {
    for arg in env::args().skip(1) {
        let reader = match arg.as_str() {
            "-" => Box::new(io::stdin()) as Box<Read>,
            path => Box::new(File::open(&path).unwrap()) as Box<Read>,
        };
    }
}

Leave a Comment