Rust Variables
Learn how to store and manage data in Rust
🦀 What are Rust Variables?
Variables in Rust store data values. By default, variables are immutable (cannot be changed) for memory safety. Use 'mut' keyword to make them mutable and changeable.
// Immutable variable
let name = "Alice";
// Mutable variable
let mut age = 25;
age = 26; // This works!
Types of Variables in Rust
Immutable Variables
Cannot be changed after creation
let x = 5;
// x = 6; // Error!
Mutable Variables
Can be changed using 'mut' keyword
let mut y = 5;
y = 6; // Works!
Type Annotations
Specify the data type explicitly
let count: i32 = 10;
let price: f64 = 19.99;
Shadowing
Reuse variable names with new values
let x = 5;
let x = x + 1; // x is now 6
🔹 Creating Your First Variable
Let's create a simple variable to store a message:
Basic Variable Syntax:
-
Use
letkeyword to declare variables - Variables are immutable by default
-
Add
mutto make them mutable - Rust infers types automatically
fn main() {
// Immutable variable
let message = "Hello, Rust!";
println!("{}", message);
// Mutable variable
let mut counter = 0;
counter = counter + 1;
println!("Counter: {}", counter);
}
Output:
Hello, Rust! Counter: 1
🔹 Mutable vs Immutable Variables
Understanding the difference between mutable and immutable variables:
🔸 Immutable Variables (Default)
- Safe: Cannot be accidentally changed
- Fast: Compiler optimizations
- Clear: Value won't change unexpectedly
- Default: Rust's preferred approach
fn main() {
let name = "Bob";
let age = 30;
println!("Name: {}, Age: {}", name, age);
// name = "Alice"; // This would cause an error!
}
🔸 Mutable Variables
fn main() {
let mut score = 0;
println!("Initial score: {}", score);
score = 10; // This works because of 'mut'
println!("Updated score: {}", score);
score += 5; // Can also use compound assignment
println!("Final score: {}", score);
}
Output:
Initial score: 0 Updated score: 10 Final score: 15
🔹 Variable Shadowing
Rust allows you to declare a new variable with the same name:
fn main() {
let x = 5;
println!("First x: {}", x);
let x = x + 1; // Shadowing with new value
println!("Second x: {}", x);
let x = x * 2; // Shadowing again
println!("Third x: {}", x);
// Can even change type with shadowing
let x = "Now I'm text!";
println!("Fourth x: {}", x);
}
Output:
First x: 5 Second x: 6 Third x: 12 Fourth x: Now I'm text!
🔹 Type Annotations
Sometimes you need to specify the variable type explicitly:
When to use type annotations:
- Ambiguous types: When Rust can't infer the type
- Specific precision: Choose between i32, i64, f32, f64
- Clarity: Make your intentions clear
fn main() {
// Explicit type annotations
let integer: i32 = 42;
let floating: f64 = 3.14159;
let boolean: bool = true;
let character: char = 'R';
let text: &str = "Rust is awesome!";
println!("Integer: {}", integer);
println!("Float: {}", floating);
println!("Boolean: {}", boolean);
println!("Character: {}", character);
println!("Text: {}", text);
}
Output:
Integer: 42 Float: 3.14159 Boolean: true Character: R Text: Rust is awesome!
🔹 Variable Naming Rules
Follow these rules when naming variables in Rust:
Naming Guidelines:
- snake_case: Use underscores between words
- Start with letter: Cannot start with numbers
- No keywords: Avoid Rust reserved words
- Descriptive: Use meaningful names
fn main() {
// Good variable names
let user_name = "Alice";
let total_score = 100;
let is_game_over = false;
let player_health = 95.5;
// Also valid (but less common)
let x = 10; // OK for short-lived variables
let _unused = 42; // Prefix with _ if unused
println!("User: {}, Score: {}", user_name, total_score);
println!("Game Over: {}, Health: {}", is_game_over, player_health);
}