Some console programs can benefit from being interactive—when the user types a string
, they print a message. This can be done with the stdin function in Rust.
By calling read_line
in a loop, we can keep accessing the data typed by the user. But to get the line we have to clear the buffer of data.
To begin, we need to include the std io module—this includes the stdin()
function that we need to call. We create a buffer string
.
read_line
on stdin in a while loop. Read_line
returns a Result
, so we call is_ok()
to ensure we get something.trim_end
to remove trailing newlines (and spaces).use std::io; fn main() { // Read in input. let mut buffer = String::new(); let stdin = io::stdin(); while stdin.read_line(&mut buffer).is_ok() { // Trim end. let trimmed = buffer.trim_end(); println!("You typed: [{trimmed}]"); buffer.clear(); } }test You typed: [test] hello You typed: [hello] friend You typed: [friend]
In my experience, having a command-line program that does one thing and exits is the easiest approach. This allows it to be called from other programs more easily.
We read lines from the command line in an interactive Rust program, and trimmed the end of the strings. A program could run certain functions based on typed input.