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

后端 未结 4 676
忘掉有多难
忘掉有多难 2020-11-29 11:59

I am attempting to write the cat command to learn Rust, but I can\'t seem to convert command line arguments into reader structs.

use std::{env,          


        
4条回答
  •  野性不改
    2020-11-29 12:33

    The accepted answer does not work with Rust v1.0 anymore. The main statement is still true though: Match arms have to return the same types. Allocating the objects on the heap solves the problem.

    use std::io::{self, Read};
    use std::fs::File;
    use std::path::Path;
    
    fn main() {
        if let Some(arg) = std::env::args().nth(1).as_ref() {
            let reader = match arg.as_ref() {
                "-"  => Box::new(io::stdin()) as Box,
                path => Box::new(File::open(&Path::new(path)).unwrap()) as Box,
            };
        }
    }
    

提交回复
热议问题