Writing to a file or stdout in Rust

I study Rust and I am a bit stumped.

I am trying to give the user the ability to write output to stdout or to the provided file name.

I started with the sample code provided for use extra::getoptslocated here . From there, in a function do_work, I try to do this:

use std::io::stdio::stdout;
use std::io::buffered::BufferedWriter;

fn do_work( input: &str, out: Option<~str> ) {
    println!( "Input:  {}", input );
    println!( "Output: {}", match out {
        Some(x) => x,
        None    => ~"Using stdout"
    } );
    let out_writer = BufferedWriter::new( match out {
        // I know that unwrap is frowned upon, 
        // but for now I don't want to deal with the Option.
        Some(x) => File::create( &Path::new( x ) ).unwrap(),
        None    => stdout()
    } );
    out_writer.write( bytes!( "Test output\n" ) );
}

But it gives the following error:

test.rs:25:43: 28:6 error: match arms have incompatible types: expected `std::io::fs::File` but found `std::io::stdio::StdWriter` (expected struct std::io::fs::File but found struct std::io::stdio::StdWriter)
test.rs:25     let out_writer = BufferedWriter::new( match out {
test.rs:26         Some(x) => File::create( &Path::new( x ) ).unwrap(),
test.rs:27         None    => stdout()
test.rs:28     } );
test.rs:25:22: 25:41 error: failed to find an implementation of trait std::io::Writer for [type error]
test.rs:25     let out_writer = BufferedWriter::new( match out {
                            ^~~~~~~~~~~~~~~~~~~

But I do not understand what the problem is, because Fileand StdWriterimplement WriterTrait. Can someone explain what I'm doing wrong?

Thank!

+4
source share
2 answers

, Write, BufWriter T, Writer, T File Stdout .

( Box<Write> &Write, , Box):

fn do_work(input: &str, out: Option<String>) {
    let mut out_writer: Box<Write> = BufWriter::new(match out {
        Some(ref x) => Box::new(File::create(&Path::new(x)).unwrap()),
        None => Box::new(stdout()),
    });
    out_writer.write(b"Test output\n").unwrap();
}

, ( ).

+3

Rust 2014 , , Rust 1.15.1:

let out_writer = match out {
    Some(x) => {
        let path = Path::new(x);
        Box::new(File::create(&path).unwrap()) as Box<Write>
    }
    None => Box::new(io::stdout()) as Box<Write>,
};

, @Arjan answer, , ~ Box, . BufferedWriter, , , BufWriter.

+6

Source: https://habr.com/ru/post/1531359/


All Articles