Closed
Description
I helped someone out with an example like this, which doesn't compile:
use std::io::{Result, Write};
fn write_stuff<W: Write>(mut writer: W) -> Result<()> {
writeln!(writer, "stuff")
}
fn main() {
let mut stdout = std::io::stdout();
writeln!(stdout, "first line").unwrap();
write_stuff(stdout);
writeln!(stdout, "second line").unwrap();
}
Compiling playground v0.0.1 (/playground)
error[E0382]: borrow of moved value: `stdout`
--> src/main.rs:11:14
|
8 | let mut stdout = std::io::stdout();
| ---------- move occurs because `stdout` has type `Stdout`, which does not implement the `Copy` trait
9 | writeln!(stdout, "first line").unwrap();
10 | write_stuff(stdout);
| ------ value moved here
11 | writeln!(stdout, "second line").unwrap();
| ^^^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `write_stuff` to borrow instead if owning the value isn't necessary
--> src/main.rs:3:38
|
3 | fn write_stuff<W: Write>(mut writer: W) -> Result<()> {
| ----------- in this function ^ this parameter takes ownership of the value
For more information about this error, try `rustc --explain E0382`.
error: could not compile `playground` (bin "playground") due to 1 previous error
The compiler suggests changing the parameter of write_stuff
to take &mut W
, but suppose you do not have control over that function. Because Read
/Write
/Sync
are implemented over mutable references of readers/writers/syncers(?), I suggested changing the code to:
write_stuff(&mut stdout);
Could the compiler detect that the type bound here is some combination of Read/Write/Sync and suggest a mutable borrow like this?