1

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
cafce25
  • 15,907
  • 4
  • 25
  • 31
Ross Youngblood
  • 502
  • 1
  • 3
  • 16

1 Answers1

3

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) {

}
cafce25
  • 15,907
  • 4
  • 25
  • 31
PitaJ
  • 12,969
  • 6
  • 36
  • 55
  • I stumbled onto the use::std::io::write myself yesterday by carefully reading the compiler error messages. So I came up with fn write_something(out_buf: &mut BufWriter) Which is essentially exactly what your first answer was. Now I need to read up on the "impl Write" solution as that appears to be the elegant solution in this case. So this solves my syntax error and allows me to keep coding, but I will have to do some reading to get my head around the impl keyword as understanding that is fundemental. Thanks so much! – Ross Youngblood Feb 02 '23 at 21:12
  • 1
    Note that `impl Trait` in parameter position is just shorthand for `T: Trait` as a function generic, with the one restriction that you can't manually provide the generic. [More info here](https://rust-lang.github.io/impl-trait-initiative/explainer/apit.html) – PitaJ Feb 02 '23 at 21:16