rust enter number from keyboard / stdin

To read a number from the keyboard or standard input (stdin) in Rust, you can use the std::io module from the standard library. Here's an example code snippet that demonstrates how to achieve this:

use std::io;

fn main() {
    let mut input = String::new();

    println!("Enter a number: ");

        .read_line(&mut input)
        .expect("Failed to read line");

    let number: i32 = input.trim().parse().expect("Invalid input");

    println!("You entered: {}", number);

In this example, we start by creating a mutable String variable called input to store the user's input. Then, we use the println! macro to display a prompt asking the user to enter a number.

Next, we use the stdin() function from the std::io module to get a handle to the standard input. We call the read_line() method on this handle, passing in a mutable reference to the input variable. This method reads a line from the input and appends it to the input string.

After that, we use the trim() method to remove any leading or trailing whitespace from the input. Then, we use the parse() method to convert the input string into an i32 (32-bit integer). If the conversion is successful, we store the result in the number variable. If the conversion fails, the program will panic and display the "Invalid input" error message.

Finally, we use the println! macro again to display the entered number.

You can run this code and try entering different numbers to see how it works.