rustbufferedwriter

Passing a BufWriter to a function in Rust


In this example I'm trying to pass a BufWriter to some functions but don't understand generic type syntax enough to figure out whats missing.
Instead of passing the file, I want to pass the buffered writer and could not find any examples of this which would get me out of the weeds.

use std::fs::OpenOptions;
use std::io::BufWriter;
fn main() {
    println!("Opening dummy read file");
    let write = OpenOptions::new()
        .write(true)
        .create(true)
        .open("DummyWriteFile");
    let mut writer = BufWriter::new(write.unwrap());
    // do some writes with FunctionA
    write_something(&mut writer);

    // write something else here with bufwriter
}

fn write_something(outBuf: BufWriter<W>) {}

The error I get is the following:

      Compiling playground v0.0.1 (/playground)
error[E0412]: cannot find type `W` in this scope
  --> src/main.rs:13:40
   |
13 | fn write_something( outBuf: BufWriter <W> ){
   |                   -                    ^ not found in this scope
   |                   |
   |                   help: you might be missing a type parameter: `<W>`

For more information about this error, try `rustc --explain E0412`.
error: could not compile `playground` due to previous error

Solution

  • You have a couple options.

    To make that version of your code work, you need to add W as a generic parameter on the function with a Write bound. And you need to change it to take a mutable reference:

    use std::io::Write;
    
    fn write_something<W: Write>(out_buf: &mut BufWriter<W>) {
    
    }
    

    But what you probably want is to use the Write trait bound (since BufWriter impls it) instead of specifying BufWriter directly:

    fn write_something(mut out_buf: impl Write) {
    // OR: fn write_something<W: Write>(mut out_buf: W) {
    
    }