Variables are the most basic building blocks a program uses to remember and compute with numbers and text.
In this part, we will walk through Rust's distinctive rules for variables, the primitive types that classify different kinds of values, and how a single semicolon changes the meaning between an expression and a statement.
1. Variables Cannot Change by Default (let and mut)
If you are new to programming, it helps to picture a variable as a storage box with a name tag on it.
You place a value like the number 10 or the text "tea" inside the box, and later call its name whenever you need to pull that value back out.
In many other languages, you can overwrite whatever is inside the box at any time. Rust takes the opposite stance.
A variable created with let is immutable by default, meaning the box locks as soon as you put a value in, and the compiler stops you before the program runs if you try to change it.1
You unlock a box only when its value genuinely needs to change by adding mut (short for mutable). That may feel strict at first, but it pays off as your code grows.
Any variable without mut is guaranteed to keep the same value from start to finish, so you spend far less time hunting down where a number quietly changed.
fn main() {
let item = "tea"; // immutable: item name
let mut quantity = 10; // mutable: order quantity
println!("Item: {}, initial quantity: {}", item, quantity);
quantity = 5;
println!("Updated quantity: {}", quantity);
}Output:
Item: tea, initial quantity: 10
Updated quantity: 5Say an order starts with ten teas and the customer changes it to five. let item = "tea"; holds the item name, which stays the same. The text from // to the end of a line is a comment; the compiler skips it.
let mut quantity = 10; leaves the quantity open to reassignment. The two {} slots in the first println! take the item and the quantity in order. After quantity = 5;, the second print reads the new count.
Remove mut from let mut quantity = 10; and compile the same program. The compiler reports cannot assign twice to immutable variable at quantity = 5;. It allows the initial value but rejects the second assignment.
It is a safety net that catches accidental overwrites before your code ever runs.
Rust also has a feature called shadowing, where you write let again with the same variable name. While mut swaps out the contents of the existing box, shadowing creates a brand-new box and moves the same name tag onto it.
That lets you transform a value and rebind it without making the original variable mutable, and the new box can even hold a different type.
2. Four Everyday Primitive Types
A computer stores the number 4 and the character '4' in completely different ways in memory. Because of that, every value carries a type that identifies what kind of data it is.
Rust is statically typed, which means the type of every value must be known at compile time before the program runs.
Even so, you do not have to write out the type every single time. Most of the time, the compiler uses type inference to figure out the type from surrounding context.
You only need to place a colon (:) after the variable name and write the type yourself when you want to make your intent explicit or when the compiler cannot tell on its own.
fn main() {
let quantity: u32 = 4; // unsigned 32-bit integer
let weight_kg: f64 = 2.5; // 64-bit floating-point number
let item_code: char = 'T'; // one Unicode scalar value
let in_stock: bool = true; // true or false
println!("quantity={}, weight={} kg, code={}, in stock={}", quantity, weight_kg, item_code, in_stock);
}Output:
quantity=4, weight=2.5 kg, code=T, in stock=trueThe order records a whole-number quantity (quantity: u32) and a weight with a fractional part (weight_kg: f64). Its item code is the single character 'T', so item_code has type char. in_stock is a bool: either true or false.2
The 32 in u32 or i32 tells you how many slots the computer uses to store that value (32 bits, or 32 tiny switches holding 0 or 1). More bits let you represent larger integers or more precise decimals.
The leading letter i stands for signed integers that allow negative numbers (i32, i64), while u stands for unsigned integers that start at 0 (u32, usize).
By giving up negative numbers, an unsigned u32 holds values from 0 up to roughly 4.2 billion.
Use u32 for an order count to make its range visible in the code. The compiler rejects -1 if you try to put it in that variable.
f64 is a 64-bit floating-point type for values such as a package weight or a coordinate that can have a fractional part.
Because char stores a single Unicode scalar value in 4 bytes, it safely holds not just the English letter 'T', but also a Korean character like 'κ°' or an emoji like 'π±' as one character.
Single quotes make 'T' a char. Double quotes make "T" a string, even though it happens to contain only one character.
When you start writing Rust, you will often bump into errors when trying to mix different numeric types in one calculation. Adding a u32 directly to an f64 triggers a "mismatched types" error from the compiler.
It can feel picky at first, but this rule prevents silent bugs where decimals get chopped off or negative values wrap around into huge positive numbers.
3. Expressions vs. Statements: One Semicolon Makes the Difference
In Part 1, we mentioned that if and blocks in Rust are expressions that produce a value.
If those terms feel abstract, think of everyday speech. A statement is like a command such as "turn off the light" that performs an action and hands nothing back, while an expression is like asking "what is 2 plus 3?" and getting a concrete value in return.
In Rust, a variable declaration like let x = 5; is a statement that does not return a value. On the other hand, a calculation like 5 + 3, a function call, and a curly-brace block { ... } are all expressions.
When you leave the semicolon (;) off the final line of a block, that line's result becomes the value of the entire block.3
fn main() {
let base = 10;
let scaled = {
let half = base / 2;
half + 3 // no semicolon, so 8 becomes the block's result
};
println!("scaled = {}", scaled);
}Output:
scaled = 8Let's trace how this runs. First, let base = 10; creates a starting value of 10. Even though no type is written, Rust automatically infers i32, the default integer type.
Next, let scaled = { ... }; stores whatever value the curly-brace block produces into scaled. Inside the block, base / 2 computes 5 and saves it in the temporary variable half, and the final line evaluates half + 3 without a semicolon. That sends 8 out of the block into scaled, and the semicolon after the closing brace finishes the outer let scaled = ...; statement.
Write half + 3; instead and the semicolon discards that result, ending the line as a statement. With nothing left to return, the block evaluates to (), the value of the unit type representing emptiness. With that semicolon after half + 3, scaled holds (), and the println! line fails with E0277 because {} cannot format that value.
Change the declaration to let scaled: i32 = and the error moves to the assignment. The block has to produce an integer, so Rust reports E0308 (expected i32, found ()) and points to the semicolon you can remove.
A single semicolon can trip you up at first. Once this rule clicks, though, if expressions and function return values in Part 3 and match in Part 6 all follow the exact same principle and fit together cleanly.
Footnotes
- The Rust Programming Language, Ch. 3.1 Variables and Mutability. https://doc.rust-lang.org/book/ch03-01-variables-and-mutability.html β©
- The Rust Programming Language, Ch. 3.2 Data Types: https://doc.rust-lang.org/book/ch03-02-data-types.html β©
- The Rust Programming Language, Ch. 3.3 Functions (Statements and Expressions). https://doc.rust-lang.org/book/ch03-03-functions.html β©