Variables and Mutability
Learn how to declare variables, why they are immutable by default, and how to use constants
Learning Objectives
- Declare variables with 'let'
- Understand the difference between immutable and mutable variables
- Learn about shadowing
- Use constants
Immutable by Default
In most languages, you can change a variable’s value after creating it. In Rust, variables are immutable by default. Once you bind a value to a name, you can’t change it.
|
|
Why Immutable?
Immutability leads to safer, more predictable code. If you know a value won’t change, you don’t have to track how and where it might be modified across your program.
Making Variables Mutable
To make a variable changeable, add the mut keyword:
|
|
Constants
Constants are similar to immutable variables, but with key differences:
- You use
constinstead oflet. - You must annotate the type.
- They can be declared in any scope, including the global scope.
- They must be set to a constant expression (something the compiler can calculate at build time).
|
|
Shadowing
In Rust, you can declare a new variable with the same name as a previous variable. This is called shadowing. The second variable “shadows” the first, taking its place.
|
|
Shadowing vs. mut
- Shadowing: We are creating a new variable. We can even change the data type of the variable while keeping the same name.
- mut: We are changing the value of the existing variable. We cannot change the type.
|
|
Summary
Today you learned:
- Variables are immutable by default for safety.
- Use
mutto allow modification. - Constants (
const) are for values that never change and require type annotation. - Shadowing allows you to reuse variable names with new values or types.
Practice Exercise
- Create a variable for your age, make it mutable, and increment it by 1.
- Define a constant for the speed of light.
- Use shadowing to convert a string
"42"into an integer42.
Next Steps
Tomorrow, we’ll explore Data Types—and see how Rust handles numbers, booleans, and compound structures!
Quiz
Complete this quiz with a minimum score of 80% to mark Day 2 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!