In Rust, reading a line from stdin typically involves using the stdin function from the std::io module and the lines method from the BufRead trait. Here is a simple example demonstrating how to read a line (string) from standard input using Rust:
rustuse std::io::{self, BufRead}; fn main() { // Create a handle to stdin let stdin = io::stdin(); // Read a line from stdin let mut line = String::new(); println!("Enter a line of text:"); match stdin.lock().read_line(&mut line) { Ok(_) => { // If successful, remove the newline character at the end of the string let line = line.trim_end(); println!("You entered: {}", line); }, Err(error) => { // If an error occurs, print the error message println!("Error reading line: {}", error); } } }
In this example, we first import the relevant parts of the std::io module. Then, in the main function, we obtain a handle to stdin and create a new empty String object to store the line to be read. We use the read_line method to read a line of user input and store it in this String object. The read_line method returns a Result type, which helps us handle potential errors. If read_line succeeds, it returns Ok, containing the number of bytes read; if it fails, it returns an Err, containing the error information. In this example, we handle the Result using pattern matching: if successful, we print the input line; if an error occurs, we print the error message.
Note that the read_line method preserves the newline character at the end of the line, so we use the trim_end method to remove trailing whitespace characters, including the newline character. This gives us a clean line string.