I'd like to store a reference to an io::Write
trait object inside an Option
in a struct but I can't figure out how. I can put the reference in directly like this:
pub struct Parameters<'a> {
pub log: &'a (io::Write + 'a),
// Other elements removed
}
and then assign it from (for example) a BufWriter
like this:
let logstream = &BufWriter::new(f);
let parameters = Parameters {
log: logstream, // Other elements removed
};
This works, but I'd like the logstream
to be optional. If I try:
pub struct Parameters<'a> {
pub log: Option<&'a(io::Write + 'a)>,
// Other elements removed
}
and
let logstream = match f {
Some(f) => Some(&BufWriter::new(f)),
None => None,
};
let parameters = Parameters {
log: logstream,
// Other elements removed
};
I get:
error[E0308]: mismatched types
--> src/main.rs:17:14
|
17 | log: logstream,
| ^^^^^^^^^ expected trait std::io::Write, found struct `std::io::BufWriter`
|
= note: expected type `std::option::Option<&dyn std::io::Write>`
found type `std::option::Option<&std::io::BufWriter<std::vec::Vec<u8>>>`
What is a suitable approach here?