I\'m trying to create a struct that has a BufWriter that uses the Write trait, so that this struct could have a buffered writer that can be anythin
Your error is in mixing generic and specific:
impl BufWriterStruct {
pub fn new(filename: &str) -> BufWriterStruct {
BufWriterStruct {
writer: Some(BufWriter::new(File::create(filename).unwrap())),
}
}
}
Here, your instance of BufWriter should accept a W: Write, which is decided by the caller, yet the function actually creates a File.
Let the caller decide, instead:
impl BufWriterStruct {
pub fn new(writer: W) -> BufWriterStruct {
BufWriterStruct {
writer: Some(BufWriter::new(writer)),
}
}
}
Of course, this will change invocation a bit:
fn main() {
let tmp = BufWriterStruct::new(File::create("tmp.txt").unwrap());
}
And then it'll work.