Rust Program to Add Two Integers

In this example, we will see how to add two numbers in the Rust program. Then we will also see how to add 2 numbers that are entered by the user. The sum of these two integers is calculated and displayed on the screen.

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

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

1. Rust Program to Add Two Integers


In this example, we have two integer numbers and a function return_sum().

How this works?


We have the main function which is the entry point of the program. we are declaring 2 variables a and b. We are specifying b of type i32 which is an explicit declaration where we are specifying the type of integer. Both variables are nonmutable so we are assigning them value once and it can not be changed later in the program.

return_sum() Function: We are calling a function return_sum() and passing both numbers to this function as arguments to do the addition task. The result will be returned by this function. We will get the resulting sum and then we will print this result using println!.

fn main() {
  let a      = 5;
  let b: i32 = 25;

  let sum = return_sum(a,  b);
  println!("The sum of a &  b is = {}", sum);
}

fn return_sum(i: i32, j: i32) -> i32 {
  i + j
}

Output

The sum of a &  b is = 30

2. Rust Program to Add Two Integers entered by User


How this Program works?


1. 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 writing traits. The second line of the program is use std::{i32} which is telling the compiler to make use of unsigned integers of 32 bits.

2. String::new():

Then the next line is to declare a mutable variable var1 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.

3. read_line() function :

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. So it means when the user will enter an input then the read_line method will read that input and put that into a string variable for which we are passing its reference.

4. expect() function:

Also, you can see 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 can fail due to any reason other than to avoid the program crashing without any notification we add the expected call. What it does is, display the message we pass to it on screen in case there is an error reported.

5. Taking Input from User

We are taking the input of the second number in var2 and for var2 also we are doing exactly the same as what we did for var1. Now we got the 2 numbers input read in the form of a String, but we expect them to be numbered. so we will need to convert them to numbers before we perform the addition. 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 the read_line() method. So to make sure we get the correct value we will make sure of the trim() method. The trim() method on the strings eliminates any special character at the beginning and end of the data and will leave only the number part.

6.Convert String input to Numeric Type

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 the parse() method which will help us to convert our string data to number format. The parse() method will give us the numbers in i32 format here.

7. Perform addition

Once we have the numbers in variables a and b then the only job left is to perform the addition. We are doing the simple addition by using the + operator. Finally printing the result by using println! ().

use std::io;
use std::{i32};

fn main() {
          // User will enter first number

          println!("Input First number ? ");

          let mut var1 = String::new();

          io::stdin().read_line(&mut var1).expect("Unable to read entered data");

          // User will enter Second number

          println!("Input second number ? ");
          let mut var2 = String::new();
          io::stdin().read_line(&mut var2).expect("Unable to read entered data");

          // Converting string to integer
          let a: i32 = var1.trim().parse().ok().expect("Program only processes numbers, Enter number");
          let b: i32 = var2.trim().parse().ok().expect("Program only processes numbers, Enter number");

          // Output of basic operations
          println!("The sum of a &  b is : {}", a + b);

}

Output

Input First number ? 5
Input second number ? 25
The sum of a &  b is : 30