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

后端 未结 4 678
忘掉有多难
忘掉有多难 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:29

    Here's a variation on Lukas's answer that avoids boxing:

    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 stdin;
            let file;
            let reader = match arg.as_ref() {
                "-"  => {
                    stdin = io::stdin();
                    &stdin as &Read
                }
                path => {
                    file = File::open(&Path::new(path)).unwrap();
                    &file as &Read
                }
            };
        }
    }
    

    The trick here is to use let bindings that are only initialized on some code paths, while still having a long enough lifetime to be able to use them as the target of a borrowed pointer.

提交回复
热议问题