Yes, both implement Write
, but the problem is BufWriter
is expecting a type T
that implements Writer
, and that T
can't be File
and Stdout
at the same time.
You must cast both to the common type (either Box<dyn Write>
or &dyn Write
, but since you cannot return references you have to use Box
):
fn do_work(input: &str, out: Option<String>) {
let mut out_writer: Box<dyn 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();
}
You should also handle errors properly, not just using unwrap
(used in example for simplicity).