How is user input of data in Rust, what is its syntax and how does it work?

Hello everyone, greetings.

I'm new to rust and I don't know how data entry works here, could someone explain to me what its syntax is and how it works?

If you want to take input from the standard input stream, here is how to do it in code:

use std::io;

fn main() {
    let mut input: String = String::new(); // Create a string variable
    io::stdin() // Get the standard input stream
        .read_line(&mut input) // The read_line function reads data until it reaches a '\n' character
        .expect("Unable to read Stdin"); // In case the read operation fails, it panics with the given message

    println!("You entered: {}", input);
}
2 Likes

Tips for fixing or avoiding some common beginner problems:

  1. read_line will append to the string you provide, rather than overwriting it. You will typically want to pass it a new empty string, or call .clear() on an existing string before re-using it.
  2. read_line will include any carriage-return / newline characters that it reads. You will typically want to call trim on the resulting string before using it.
  3. You can use the parse method to convert the input string into a number or other type. (Remember to call .trim() before .parse() to avoid errors!)
6 Likes

Putting a few tricks together for a common type of program where you read commands in a loop:

for line in std::io::stdin().lines() {
  let mut args = line.split();
  match args.next() {
    None => continue,
    Some("get") => {
      let name = args.next();
      // ...
    }
    // ...
    Some(command) => {
      println!("Unknown command: {command}");
    }
  }
}