In Rust, variable declaration is straightforward but comes with some unique characteristics compared to other programming languages. Here’s an overview of how to declare and use variables in Rust:
Variable Declaration Syntax
The basic syntax for declaring a variable is:
let variable_name = value;
Key Features of Variable Declaration in Rust
Immutable Variables (Default)
• By default, variables in Rust are immutable, meaning their value cannot be changed once assigned.
fn main() {
let x = 10; // Immutable variable
println!("x is: {}", x);
// x = 20; // ERROR: cannot assign twice to immutable variable
}
Mutable Variables
• Use the mut keyword to make a variable mutable, allowing its value to change.
fn main() {
let mut x = 10; // Mutable variable
println!("x is: {}", x); //output: x is: 10
x = 20; // Changing the value
println!("x is now: {}", x); //output: x is now: 20
}
Type Inference
• Rust infers the type of a variable based on the value assigned to it. However, you can explicitly specify the type if needed.
fn main() {
let x = 10; // Type inferred as i32
let y: f64 = 3.14; // Explicitly specifying the type
println!("x: {}, y: {}", x, y); // Output x: 10 , y: 3.14
}
Shadowing
• You can declare a new variable with the same name as an existing one, which “shadows” the previous variable. This is useful for transformations or type changes while keeping the variable immutable.
fn main() {
let x = 5;
let x = x + 1; // Shadowing
let x = x * 2;
println!("The value of x is: {}", x); // Output: 12
}
Constants
• Use the const keyword to define a constant. Constants must have an explicit type and are always immutable.
const MAX_POINTS: u32 = 100_000; // Constant with explicit type
fn main() {
println!("Max points: {}", MAX_POINTS);
}
Multiple Variables Declaration
• You can declare multiple variables in a single let statement using pattern matching.
fn main() {
let (x, y, z) = (1, 2, 3); // Declare multiple variables
println!("x: {}, y: {}, z: {}", x, y, z);
}
Common Data Types for Variables
Type | Description | Example |
i32 | 32-bit signed integer | let x: i32 = -42; |
u32 | 32-bit unsigned integer | let x: u32 = 42; |
f64 | 64-bit floating-point | let pi: f64 = 3.14; |
bool | Boolean | let is_true: bool = true; |
char | Single Unicode character | let letter: char = ‘A’; |
&str | String slice (borrowed) | let greeting = “Hello”; |
Examples of Variable Declarations
Basic Declaration
fn main() {
let name = "Alice";
let age: u32 = 30; // Explicit type
println!("Name: {}, Age: {}", name, age);
}
Using mut for Mutability
fn main() {
let mut counter = 0;
println!("Counter: {}", counter);
counter += 1; // Increment the counter
println!("Counter after increment: {}", counter);
}
Shadowing Example
fn main() {
let x = 5; // Immutable
let x = x + 1; // Shadowing the previous x
let x = x * 2; // Shadowing again
println!("Final value of x: {}", x); // Output: 12
}