Rust Program to Print an Integer (Entered by the User)

Print an Integer (Entered by the User)

Rust Programming Language

Print an Integer (Entered by the User)


Rust program that prompts the user to enter an integer and then prints it.


use std::io;

fn main() {
    println!("Please enter an integer:");

    let mut input = String::new();
        .read_line(&mut input)
        .expect("Failed to read line");

    let integer: i32 = match input.trim().parse() {
        Ok(num) => num,
        Err(_) => {
            println!("Invalid input, please enter an integer");

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


Please enter an integer:
You entered: 42{codeBox}


In this example, we use Rust's standard library's io module to read input from the user. We first print a prompt to the console using println!("Please enter an integer:");.

We then create a new String called input and use the stdin() function from the io module to read a line of input from the user into input.

We then use Rust's match expression to parse the input string into an integer. If the parsing is successful, we store the resulting integer in a variable called integer and print it to the console using println!("You entered: {}", integer);. If the parsing fails, we print an error message and return early using return;.

This shows the program prompting the user for input, the user entering the integer 42, and the program printing the entered integer to the console.

Post a Comment