I’d like to have a function that either writes to stdout or to a Vec. This is for an interactive CLI I would like to write tests for.
This works:
// To stdout
write!(std::io::stdout(), "{}", "fooxn".to_string()).unwrap();
// To a Vec<u8>
let mut vec_buf = Vec::new();
write!(vec_buf, "{}", "foox".to_string()).unwrap();
print!("Via string: {:?}", std::str::from_utf8(&vec_buf).unwrap());
But when I try something like this:
fn write_stuff(w: &mut Box<dyn Write>) {
write!(w, "foo");
}
I can run it with stdout:
let mut buf = Box::new(io::stdout()) as Box<dyn Write>;
write_stuff(&mut buf);
I can run it with a Vec<u8>
:
let mut buf = Box::new(Vec::new()) as Box<dyn Write>;
write_stuff(&mut buf);
But then, how can I assert the contents after the call?
print!("Via string: {:?}", std::str::from_utf8(&buf).unwrap());
Results in:
error[E0308]: mismatched types
--> src/pipeline.rs:96:56
|
96 | print!("Via string: {:?}", std::str::from_utf8(&buf).unwrap());
| ------------------- ^^^^ expected `&[u8]`, found `&Box<dyn Write>`
| |
| arguments to this function are incorrect
|
= note: expected reference `&[u8]`
found reference `&Box<dyn std::io::Write>`