Lesson 3: Variables and Data Types in Rust
Understanding Variables in Rust
In Rust, variables are used to store values that your program uses or manipulates. Rust’s approach focuses on safety and clarity.
Immutable by Default
By default, variables in Rust cannot be changed after they are set (they are immutable). This makes programs safer and easier to reason about.
fn main() {
let name = "Rustacean";
println!("Hello, {}!", name);
}
let name = "Rustacean";
declares a variable namedname
.- Because it’s immutable, you cannot do
name = "NewName";
later without an error.
Making Variables Mutable
If you need to change a variable’s value, use mut
:
fn main() {
let mut counter = 1;
println!("Counter is: {}", counter);
counter = 2;
println!("Counter is now: {}", counter);
}
let mut counter = 1;
means you can changecounter
later.
Common Data Types
Rust is a statically typed language—types of all variables must be known at compile time. Here’s an overview:
Type | Example | Description |
---|---|---|
Integer | let x = 5; | Whole numbers: i32 , u32 , etc. |
Float | let y = 2.5; | Decimal numbers: f32 , f64 |
Boolean | let b = true; | true or false |
Char | let c = 'A'; | Single Unicode character |
String | let s = "hi"; | Text (string slices or String ) |
Example: Declaring Different Types
fn main() {
let age: u32 = 30;
let height: f32 = 1.75;
let is_programmer: bool = true;
let grade: char = 'A';
let language: &str = "Rust";
println!("Age: {}, Height: {}, Programmer: {}, Grade: {}, Language: {}", age, height, is_programmer, grade, language);
}
Type Annotations
Rust can usually infer types, but you can add them for clarity, as above.
Interactive Task 1: Try It Yourself
Change the values of the above variables to match your own details (your age, height, etc.) and run the program.
- What happens if you try to change
age
without making itmut
?
The Power of Shadowing
You can declare a new variable with the same name as a previous variable—this is called shadowing.
fn main() {
let score = 10;
let score = score + 15; // shadows previous `score`
println!("Final score: {}", score);
}
- Shadowing is useful when transforming values (e.g., changing type or modifying value).
Mini-Challenge
- Declare a mutable variable named
temperature
with a value of25
. - Increase it by
5
and print the updated value.
fn main() {
// Your code here!
}
Try the challenge and share your solution in the comments!
Solution: https://gist.github.com/rust-play/bd9370f45a6ea5baf4bd6c8b62097635
Recap
- Variables are immutable by default, but can be made mutable with
mut
. - Rust’s data types include integers, floats, booleans, characters, and strings.
- Type annotations add clarity or are required in ambiguous cases.
- Shadowing lets you reuse variable names for value transformations.
Go to Course Structure or Navigate to next blog!