You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Rust has a rich type system designed for safety and expressiveness. Variables are immutable by default, and the compiler infers types whenever possible while enforcing strict type safety.
In Rust, variables are immutable by default:
let x = 5;
x = 6; // ERROR: cannot assign twice to immutable variable
To make a variable mutable, use the mut keyword:
let mut x = 5;
x = 6; // OK
Tip: Preferring immutability makes code easier to reason about. Only use
mutwhen you actually need to change a value.
Constants are always immutable and must have a type annotation:
const MAX_POINTS: u32 = 100_000;
| Feature | let | const |
|---|---|---|
| Mutability | Can be mut | Always immutable |
| Type annotation | Optional (inferred) | Required |
| Computed at | Runtime | Compile time |
| Scope | Block scope | Any scope (including global) |
Rust allows you to declare a new variable with the same name, shadowing the previous one:
let x = 5;
let x = x + 1; // x is now 6
let x = x * 2; // x is now 12
// Shadowing can even change the type:
let spaces = " "; // &str
let spaces = spaces.len(); // usize
Shadowing is different from mut because you are creating a new variable each time. This is useful for transforming a value while keeping the same name.
Rust has four primary scalar types:
| Length | Signed | Unsigned |
|---|---|---|
| 8-bit | i8 | u8 |
| 16-bit | i16 | u16 |
| 32-bit | i32 | u32 |
| 64-bit | i64 | u64 |
| 128-bit | i128 | u128 |
| Architecture | isize | usize |
The default integer type is i32. The isize and usize types depend on the platform (32-bit or 64-bit).
Integer literals can use different formats:
| Format | Example |
|---|---|
| Decimal | 98_222 |
| Hex | 0xff |
| Octal | 0o77 |
| Binary | 0b1111_0000 |
Byte (u8 only) | b'A' |
let x = 2.0; // f64 (default)
let y: f32 = 3.0; // f32
| Type | Precision |
|---|---|
f32 | Single precision (32-bit) |
f64 | Double precision (64-bit, default) |
let t = true;
let f: bool = false;
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.