OneBite.Dev - Coding blog in a bite size

Declare An Integer In Rust

Code snippet for how to Declare An Integer In Rust with sample and detail explanation

In this article, we’re going to discuss how to declare an integer in Rust. This is fundamental knowledge for anyone learning to code in Rust as integers are one of the basics datatypes you’ll encounter while developing applications in this language.

Code snippet for Declaring an Integer in Rust

fn main() {
    let x: i32 = 42;
    println!("{}", x);
}

Code Explanation for Declaring an Integer in Rust

To begin with, you’ll notice the structure of a basic Rust program. The fn main() declaration is the entry point to any Rust program. This code block is where your Rust application begins execution.

The piece of code let x: i32 = 42; is what actually declares our integer. Here, let is a keyword that allows you to introduce a new variable into your code. The x immediately following let is the name of our variable.

Rust is a statically typed language, which means it must know the types of all variables before they are actually run. For this purpose, following the variable name, we have : i32 which instructs the Rust compiler that our variable x is a 32-bit integer.

The symbol = is used for assignment, followed by the value to be assigned to the variable, in this case 42.

Finally, the println!("{}", x); is used to print the value stored in x to the console.

Now, when you run this program, the Rust compiler will execute the code inside fn main(), which is going to initialize x as 42 and print out its value, so you will see 42 printed to your console.

Thus, this code snippet illustrates how to declare a 32-bit integer variable in Rust, assign it a value, and then print that value to the console. This concept is foundational and can be expanded on to create more complex operations and functions in Rust.

rust