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 anything that implements that trait: File
, Stream
, etc. But I'm having an issue in my function that creates the struct saying that I have mismatched types
. Here is an example code with the same issue.
use std::fs::File;
use std::io::{BufWriter, Write};
pub struct BufWriterStruct<W: Write> {
pub writer: Option<BufWriter<W>>,
}
impl <W: Write>BufWriterStruct<W> {
pub fn new(filename: &str) -> BufWriterStruct<W> {
BufWriterStruct {
writer: Some(BufWriter::new(File::create(filename).unwrap())),
}
}
}
fn main() {
let tmp = BufWriterStruct::new("tmp.txt");
}
with the error
error: mismatched types:
expected `BufWriterStruct<W>`,
found `BufWriterStruct<std::fs::File>`
If instead I change my new
function to instead take a parameter that implements the Write
trait and use that when creating BufWriter
, it works fine.
I feel like the former should be possible to do somehow.
See Question&Answers more detail:os