When we learning Rust programming, one of the first and most important concepts is variables because it’s a building blocks of any program that allows us to store and manipulate data.
Rust programming is different from other languages because it treats variables with immutability by default. This means once you create a variable, you can’t change its value unless you explicitly make it mutable.
This method helps us to write safe, predictable, and bug-free code, which is one of Rust’s main goals.
We will covered the:
- How To Declare Variables In Rust?
- Mutable and Immutable Variables In Rust
- Variable Shadowing In Rust
- Constants In Rust
- Variable Scope In Rust
- Beginners-friendly Example of Variables
- Your Exercise of Variables
How To Declare Variables In Rust?
A variable is a named storage location that can hold a value. Every variable has a name (identifier), a value (the data it holds), and a data type ( like integer, float, string, etc.).
Rust has strict rules for variable declarations, which helps prevent unexpected bugs.
Click on the URL and set up Rust on your system.
Variables are declared using the let keyword in Rust. For example:
fn main() {
let age = 25;
println!("My age is {}", age);
}
You can see:
- A let keyword declares a variable.
- age is the variable name.
- 25 is the value assigned to it.
Mutable and Immutable Variables In Rust
1) Immutable Variable
Rust variables are immutable by default, which means we cannot change their value after assignment. If you are trying to modify an immutable variable, Rust will throw a compile-time error.
For example:
fn main() {
let age = 25;
println!("Age: {}", age);
age = 30; // Error! Can't change because 'age' is immutable
}
See this code carefully. Rust will stop a program before running because it prevents accidental changes to values.
2) Mutable Variables
If you want to change the variable values, you need to first convert its value to mutable by the mut keyword.
For example:
fn main() {
let mut score = 10;
println!("Initial score: {}", score);
score = 15; // Allowed because 'score' is mutable
println!("Updated score: {}", score);
}
We use the mut keyword for this code to allow us to change its value. And we can now modify the score multiple times without any error.
What Is Variable Shadowing in Rust?
Shadowing allows us to declare a new variable with the same name as an existing variable. But shadowing doesn’t modify the original variable.
Shadowing example:
fn main() {
let price = 50;
println!("Original price: {}", price);
let price = price + 20; // Shadowing
println!("Discounted price: {}", price);
}
In short, Shadowing is useful when you want to transform a variable’s value without making it mutable.
What Is Constants In Rust?
Constants are a type of variable, but their value is fixed and cannot be changed. We can declare them using the const keyword with the data type explicitly.
Simple example of Rust const variable:
const MAX_USERS: u32 = 1000;
fn main() {
println!("The maximum allowed users: {}", MAX_USERS);
}
Important points about constants:
- Always use uppercase names with underscores by convention.
- Must define a data type.
- It can be declared outside of functions (global scope).
What Is Variable Scope In Rust?
Rust follows block scope rules, which means variables only exist within the block {} where they are declared.
fn main() {
let username = "Alice";
{
let username = "Bob"; // Shadowing in inner block
println!("Inside block: {}", username);
}
println!("Outside block: {}", username);
}
Output:
Inside block: Bob
Outside block: Alice
You can see, the username variable doesn’t affect that the outside of variable.
Beginner-Friendly Example with Variables
Now, we will create a Rust program using variables, mutability, constants, and shadowing together.
This program calculates the total bill for a shopping cart with tax.
const TAX_RATE: f32 = 0.08; // 8% tax rate
fn main() {
let item_price = 120.0;
let mut quantity = 3;
println!("Initial quantity: {}", quantity);
// Increasing quantity
quantity = quantity + 2;
// Shadowing: applying tax calculation
let total_price = item_price * quantity as f32;
let total_price = total_price + (total_price * TAX_RATE);
println!("Final quantity: {}", quantity);
println!("Total bill (with tax): {:.2}", total_price);
}
Output of this program:
Initial quantity: 3
Final quantity: 5
Total bill (with tax): 648.00
First, we declare a constant tax rate, then use the mut keyword to change the quantity.
Next, we use shadowing for the total_price to calculate tax without making it mutable, and then print the final bill.
You Exercise of Rust Variables
Practice this simple two questions:
- I created a variable year = 2025, but when I try to change it to 2030, Rust gives me an error. Why does this happen, and how can I fix it so I can change the value?
- I set price = 100, but now I want to:
- Add 20 to it, and then make it print as “120 USD” (as a string).