Variables and Mutability
In Rust, variables are immutable by default. This is one of Rust's key features that helps you write safer, more predictable code.
Declaring Variables
Use the let keyword to declare variables:
The code above creates an immutable variable x with the value 5. If you try to change it, Rust will give you a compile-time error.
Mutable Variables
To make a variable mutable, use the mut keyword:
mut when you actually need to change a variable. Immutability by default helps prevent bugs.Constants
Constants are similar to immutable variables, but with key differences:
Constants vs Variables:
- Constants use
constinstead oflet - You must annotate the type (e.g.,
u32) - Constants can be declared in any scope, including global
- Constants must be set to a constant expression, not computed at runtime
- Naming convention: SCREAMING_SNAKE_CASE
Shadowing
Rust allows you to declare a new variable with the same name as a previous variable. This is called shadowing:
Shadowing vs Mutability:
Shadowing is different from marking a variable as mut. With shadowing, you're creating a new variable, which means you can even change its type:
Practice Exercise
Try to predict what this code will output: