Type annotations needed on Writer

Hello friends,

I've been building a parser, reader + writer, and I get the compiler telling me I need type annotations to compile. I'd ideally like to add a bit of code so I don't need to add these annotations as the API becomes a bit more annoying. My code is as such:

pub struct Writer<W: io::Write> {
    pub wtr: io::BufWriter<W>,
}

impl<W: io::Write> Writer<W> {
    pub fn new(wtr: W) -> Writer<W> {
        Writer {
            wtr: io::BufWriter::new(wtr),
        }
    }
    //
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Writer<File>> {
        Ok(Writer::new(File::create(path)?))
    }
    // other fields...
}

Now when I try and call Writer:

let mut writer = Writer::from_path("./test.refer")?; // fails
let mut writer = Writer::<Vec<u8>>::from_path("./test.refer")?; // okay!

I'm sure this is something to do with traits that I don't understand. Many thanks,
M

In this case, the W type in your Writer is known, so you can put the from_path() method in a impl Writer<File> block.

impl<W: io::Write> Writer<W> {
    pub fn new(wtr: W) -> Writer<W> {
        Writer {
            wtr: io::BufWriter::new(wtr),
        }
    }
}

impl Writer<File> {
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        Ok(Writer::new(File::create(path)?))
    }
}
1 Like

The impl block you're referring to in the first case is ambiguous (and Rust can't tell whether or not you use W in the from_path impl externally).

Try placing the from path impl in a specialized impl block:

impl Writer<File> {
    ...
}
2 Likes

Brilliant thank you, that's exactly what I needed!
M

Brilliant, sorry saw the reply below first but this exactly works :slight_smile: Thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.