31

All the documentation I've found regarding flushing suggests that the proper way to flush stdout is as follows:

std::io::stdout().flush().expect("some error message");

This results in

no method named flush found for type std::io::Stdout in the current scope

What am I doing wrong?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
River Tam
  • 3,096
  • 4
  • 31
  • 51

2 Answers2

49

You need to import the trait that implements the flush method for Stdout.

According to the documentation:

io::Write

Therefore:

use std::io::Write; // <--- bring the trait into scope

fn main() {
    std::io::stdout().flush().expect("some error message");
}

Playground example

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
19

Can anyone tell me what I'm doing wrong?

Yes; the compiler already does.

fn main() {
    std::io::stdout().flush().expect("some error message");
}
error[E0599]: no method named `flush` found for type `std::io::Stdout` in the current scope
 --> src/main.rs:3:23
  |
3 |     std::io::stdout().flush().expect("some error message");
  |                       ^^^^^
  |
  = help: items from traits can only be used if the trait is in scope
  = note: the following trait is implemented but not in scope, perhaps add a `use` for it:
          candidate #1: `use std::io::Write;`

Emphasis on the help and note lines - use std::io::Write.

All together:

use std::io::Write;

fn main() {
    std::io::stdout().flush().expect("some error message");
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366