Exerpad
🔥1
10 XP
Lv.1 Beginner
Log In

What are Variables?

A variable is like a labeled box that stores a value. You give the box a name, and you can put something inside it.

Creating Variables

In Rust, use let to create a variable:

rust
fn main() {
let name = "Alex";
let age = 10;
println!("{}", name);
println!("{}", age);
}

Output:

text
Alex
10

Types of Values

Strings — text inside double quotes:

rust
fn main() {
let color = "blue";
let greeting = "Hello!";
println!("{}", color);
println!("{}", greeting);
}

Integers — whole numbers:

rust
fn main() {
let score: i32 = 100;
let lives: i32 = 3;
println!("{}", score);
println!("{}", lives);
}

Decimals — numbers with a dot:

rust
fn main() {
let height: f64 = 4.5;
let pi: f64 = 3.14;
println!("{}", height);
println!("{}", pi);
}

Booleans — true or false:

rust
fn main() {
let is_happy = true;
let is_raining = false;
println!("{}", is_happy);
println!("{}", is_raining);
}

Type Annotations

Rust can usually figure out the type, but you can also write it yourself:

rust
fn main() {
let name: &str = "Alex";
let age: i32 = 10;
let height: f64 = 4.5;
let is_cool: bool = true;
println!("{} is {} years old", name, age);
}

Immutable by Default

In Rust, variables cannot be changed unless you say so! This code would cause an error:

text
let score = 0;
score = 100;  // Error! Can't change an immutable variable

Mutable Variables

Add mut to let Rust know you want to change the variable later:

rust
fn main() {
let mut score = 0;
println!("{}", score);
score = 100;
println!("{}", score);
}

Output:

text
0
100

Shadowing

In Rust, you can create a new variable with the same name. This is called shadowing:

rust
fn main() {
let x = 5;
let x = x + 1;
println!("{}", x);
}

Output:

text
6

Shadowing creates a brand new variable — it doesn't change the old one.

Printing with Variables

Use {} inside println!() as a placeholder for variables:

rust
fn main() {
let name = "Alex";
let age = 10;
println!("My name is {}", name);
println!("I am {} years old", age);
}

Output:

text
My name is Alex
I am 10 years old