I would like to create a vector of trait objects that I can iterate over. However, I am having trouble because my trait is not object-safe. Is it the fact that my write() method takes a reference to a Write trait? Is there a way around this?
use std::io::{Write};
use std::boxed::Box;
trait FormatOutput {
fn write<T: Write>(&self, w: &mut T);
}
struct FormatOutputImpl;
impl FormatOutput for FormatOutputImpl {
fn write<T: Write>(&self, w: &mut T){
w.write(format!("hello world!\n").as_bytes()).unwrap();
}
}
fn main() {
let mut fov: Vec<Box<FormatOutput>> = Vec::new();
fov.push(Box::new(FormatOutputImpl));
}
This generates the following output:
cargo build
Compiling hello-world v0.1.0 (file:///work/tmp)
src/main.rs:17:14: 17:40 error: cannot convert to a trait object because traitFormatOutput
is not object-safe [E0038]
src/main.rs:17 fov.push(Box::new(FormatOutputImpl));