-1

This code shows an error:

fn main() {
    let mut writer = std::io::BufWriter::new(std::io::stdout().lock());
}
error[E0716]: temporary value dropped while borrowed
  --> src\main.rs:5:46
   |
5  |     let mut writer = std::io::BufWriter::new(std::io::stdout().lock());
   |                                              ^^^^^^^^^^^^^^^^^        - temporary value is freed at the end of this statement
   |                                              |
   |                                              creates a temporary which is freed while still in use
...
12 | }
   | - borrow might be used here, when `writer` is dropped and runs the `Drop` code for type `BufWriter`
   |
   = note: consider using a `let` binding to create a longer lived value

This code works:

fn main() {
    let stdout = std::io::stdout();
    let mut writer = std::io::BufWriter::new(stdout.lock());
}

How is the borrow checker working here?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366

1 Answers1

0

Stdout::lock returns a StdoutLock instance that borrows the Stdout that created it. In other words, the StdoutLock can last not longer than the Stdout that created it. As the compiler error suggests, the Stdout (created and returned by std::io::stdout()) is a temporary value which is freed right after use, invalidating the Stdout reference inside the StdoutLock (created by std::io::stdout().lock()). To prevent this from happening, you must give the Stdout returned by std::io::stdout() an explicit lifetime that outlasts the StdoutLock by binding it to a variable.

EvilTak
  • 7,091
  • 27
  • 36