The following code works to repeatedly prompt a user for input.
But I don't understand why I have to pull in the Write
trait when my code doesn't explicitly use it.
use std::io::{stdin, stdout, Write}; // can't call flush below unless Write is included here - Why?
fn main() {
let mut buffer = String::new();
loop {
print!("Command: ");
// The flush method returns a Result enum value.
// If it is Ok, the expect method returns the value it contains.
// If it is Err, it panics with the supplied message.
stdout().flush().expect("failed to flush");
// The read_line method also returns a Result enum value.
stdin().read_line(&mut buffer).expect("failed to read");
buffer.pop(); // removes newline from end of buffer
if buffer == "quit" {
break;
}
println!("You entered {}.", buffer);
buffer.clear(); // prepares to reuse buffer
}
}