Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

Rust Variables

A variable is a name for a value, like a label on a jar. You put something in the jar, stick a label on it, and later you can ask for the jar by its label instead of remembering what was inside. In Rust you create a variable with the word let.

fn main() {
    let city = "Pune";
    let year = 2025;
    println!("{} in {}", city, year);
}
Output
Pune in 2025

Variables do not change, unless you ask

Here is the first thing that surprises people coming from other languages: in Rust, a variable cannot be changed after you give it a value. It is immutable by default. This is on purpose. Most values in a program never need to change, and when the compiler knows that, it can stop a whole kind of mistake where some code changes a value that other code was relying on.

When you really do want a variable that changes, you say so with mut, short for mutable:

fn main() {
    let mut score = 0;
    println!("Start: {}", score);
    score = score + 10;
    score += 5;
    println!("Now: {}", score);
}
Output
Start: 0
Now: 15

score += 5 is a short way of writing score = score + 5. Try deleting the mut in the editor and running the program: the compiler explains that you cannot assign twice to an immutable variable, and even suggests adding mut.

Shadowing: a new variable with the same name

Rust also lets you declare a new variable with the same name as an old one, using let again. The new one shadows the old one: from that line on, the name means the new value. This is useful when you transform a value step by step and the old version is no longer needed.

fn main() {
    let price = 100;
    let price = price * 2;
    let price = price - 30;
    println!("Final price: {}", price);
}
Output
Final price: 170

Shadowing is different from mut. Each let makes a fresh variable, so it can even have a different type: let input = "42"; followed by let input: i32 = input.parse().unwrap(); turns text into a number while keeping the friendly name.

Naming variables

Variable names in Rust use lowercase letters with underscores between words, like total_price or first_name. This style is called snake case. Names can contain letters, digits and underscores, but cannot start with a digit. Choose names that say what the value means: marks is far kinder to a reader than m.

Practice exercises

  1. Create variables for your name and your age, and print them in one sentence.
  2. Make a mutable variable steps, add 500 to it three times, and print the result.
  3. Use shadowing to take a temperature in Celsius, multiply it by 9, divide by 5, and add 32.