Rust Program to Print Integer Entered by User

Rust-Programs

In this example, We will learn a simple Rust Program to Print Integer Entered by User. The integer entered by the user is stored in a variable and printed on the screen.

To understand this example, you should have knowledge of the following Rust programming topics:

  • Rust Variables, Constants and Literals
  • Rust Data Types
  • Rust Input-Output (I/O)

1. Rust Program to Print Integer enetered by user


In this example, we are taking integer number input from the user and printing the number on the console.

use std::io;

fn main() {
    let mut input_data = String::new();
    io::stdin()
        .read_line(&mut input_data)
        .expect("Unable to read from stdin");

    let trim_data = input_data.trim();
    match trim_data.parse::<u32>() {
        Ok(i) => println!("Your integer input: {}", i),
        Err(..) => println!("You entered an non Integer value: {}", trimmed),
    };
}

Output

//When you read 123
$rustc -o main *.rs
$main
Your integer input: 123

//When you read "abc"
$rustc -o main *.rs
$main

You entered an non Integer value: abc

How does it works?


Use std::io module

The first line of the program is to include the std::io module of Rust. This module has a lot of functionality, but its main use is to provide support for reading and write traits.

Declaring variables Using String::new(),mut

Then the next line is to declare a mutable variable input_data and it will be of type string as we are doing a String::new() for this. We are declaring it as mutable because we will be using this to save the input from the user. If we don’t add the mut keyword then this will be throw error when we will try to assign it a value later in the program.

Read_line() method

Next, we are making use of the read_line() method from the std::io module.The read_line() method takes a &mut String as an argument, which means reference of a mutable String. when the user will enter an input the read_line() method will read that input and put that into a string variable for which we are passing its reference.

Expect() function:

Also we are making use of expect() function also which is used for error handling in Rust. This is not mandatory to call but in Rust, we prefer to call this because if we don’t call this then we will be flagged by the compiler with a warning.

There is the possibility that the read_line() method may fail due to any reason to avoid the program crashing without any notification we add the expect() call. What it does is, display the message we pass to it on screen in case there is an error reported.

Removing Special character

Now we got the input read in the form of a String, but we expect it to be a number. so we will need to convert it to a number. Before we apply the conversion, we will need to make sure the String that we are going to convert does not have any special characters in it.

This is important in Rust because when the user will enter the number and presses enter, it may add a \n new line to the String that we will get from read_line() method. So to make sure we get the correct value we will make sure of trim() method. The trim() method on the strings eliminates any special characters at the beginning and end of the data and will leave only the number part.

Convert to Numeric DataType Using parse() method

Since we have the number in a string now, so our next step is to convert it to a numeric data type. In Rust, we have different formats to save numeric values like i32,i64,u32,u64 which means integer 32 bit, integer 64 bit, etc.

We are making use of parse() method which will help us to convert our string data to number format. As per the syntax requirements of parse() method we will need to specify the type of integer we want from it.so if you see we are calling like this parse::(), which means we want an unsigned 32-bit number.

Error Handling

The last part is again an error handling to make sure used entered the number or a non-number input.