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:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.