|
| 1 | +/// Use `Write` so that `writeln!()` and `write!()` work. |
| 2 | +/// Use `BufRead` so that `stdin.read_line()` works. |
| 3 | +use std::io::{self, Write, BufRead}; |
| 4 | + |
| 5 | +fn main() { |
| 6 | + // Get a handle to stdout. Note that we are not bothering to lock it, because we don't care |
| 7 | + // about performance and there's no `BufWrite` trait. |
| 8 | + let mut stdout = io::stdout(); |
| 9 | + // This could just as easily have been `println!()`. |
| 10 | + writeln!(stdout, "Trying some stuff").unwrap(); |
| 11 | + // Print a prompt and leave the cursor there. |
| 12 | + write!(stdout, "> ").unwrap(); |
| 13 | + // Without this the prompt won't appear until way late. |
| 14 | + stdout.flush().unwrap(); |
| 15 | + // Get a handle to stdin. Note that this must be a separate step from locking, because the |
| 16 | + // locking borrows the handle. |
| 17 | + let stdin = io::stdin(); |
| 18 | + // Get a locked `StdinLocked` guard. This obeys `BufRead`. |
| 19 | + let mut stdin = stdin.lock(); |
| 20 | + // Make a placeholder to read a line of text into. |
| 21 | + let mut msg = String::new(); |
| 22 | + // Read a line of text as a side effect in `msg`. |
| 23 | + let _ = stdin.read_line(&mut msg).unwrap(); |
| 24 | + // Show the line, trimming off the line ending (and any whitespace). |
| 25 | + eprintln!("Got {}", msg.trim_end()); |
| 26 | +} |
0 commit comments