Add Two Numbers In Rust
Code snippet for how to Add Two Numbers In Rust with sample and detail explanation
In this article, we will explore how to add two numbers in Rust, a modern systems programming language from Mozilla. This simple operation allows you to understand some basic features and syntax of Rust.
Code Snippet
Firstly, we will begin with a simple piece of code that adds two numbers in Rust.
fn main() {
let num1 = 5;
let num2 = 10;
let sum = num1 + num2;
println!("The sum of {} and {} is {}", num1, num2, sum);
}
Code Explanation
Let’s go through the code step by step to understand it better.
The first line, fn main() {
declares the main function area which is the starting point for any Rust program.
Next, we declare two integer variables, num1
and num2
, and assign them the values 5 and 10 respectively. This is done by saying let num1 = 5;
and let num2 = 10;
. The let
keyword is used for declaring or initializing variables.
The line let sum = num1 + num2;
is where the addition operation happens. Here, a new variable called sum
is initialized and it’s assigned the value of num1 + num2
, i.e., the addition of the values stored in num1
and num2
.
Finally, we output the result on the console with the line println!("The sum of {} and {} is {}", num1, num2, sum);
. The println!
macro is used for printing to the system console. The {}
within the string are placeholders for variables, and these variables are passed in the order they should appear at the end of the statement.
And there you have it, a simple program to add two numbers in Rust! This program represents some of the fundamental aspects of programming - working with variables and doing arithmetic operations.