Variables, Mutability, and Shadowing
Understand how to declare variables, manage mutability, and use shadowing for flexible variable redefinition.
Variables, Mutability, and Shadowing is a free Learn Rust Coding lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Intro to Rust Variables
Welcome! In Rust, variables are fundamental for storing data. They're like labeled boxes where you keep information your program needs.
Rust has a strong focus on safety, and this starts with how it handles variables. You'll learn how to declare them, control their changeability, and even 'redefine' them in clever ways.
Declaring Variables with `let`
To create a variable in Rust, we use the let keyword. This assigns a name to a value. Rust often infers the type, so you don't always need to specify it.
Try running this simple example:
fn main() {
let apples = 5;
println!("I have {} apples.", apples);
}Rust's Immutability Default
A key concept in Rust is that variables are immutable by default. Once you assign a value to a variable, you cannot change it later.
This might seem restrictive, but it helps prevent bugs and makes your code safer and easier to reason about, especially in concurrent programming.
Making Variables Mutable with `mut`
If you need a variable's value to change, you can explicitly make it mutable using the mut keyword before the variable name.
This tells Rust (and other developers) that this variable's value is intended to be changed.
fn main() {
let mut score = 100;
println!("Initial score: {}", score);
score = 150; // We can change it now!
println!("New score: {}", score);
}When to Use `mut`
While mut is powerful, it's good practice to use it only when necessary. Prefer immutability as your default.
- Use
mutfor counters, state variables, or values that genuinely need to be updated. - If a value never changes after its initial assignment, keep it immutable (no
mut). - Clarity: Explicitly marking a variable as
mutmakes your code's intent clearer.
Defining Constants with `const`
Constants are special types of immutable variables. They are declared with the const keyword instead of let, and they must always have their type explicitly annotated.
Constants can only be set to constant expressions, not the result of a function call or any value that could only be computed at runtime.
fn main() {
const MAX_USERS: u32 = 10_000; // Type annotation is required!
println!("Max users allowed: {}", MAX_USERS);
}`let` Variables vs. `const` Constants
Here are the key differences between let variables and const constants:
- Mutability:
letvariables are immutable by default but can be made mutable withmut.constconstants are always immutable. - Declaration:
letuseslet.constusesconst. - Type Annotation:
letvariables can often infer their type.constconstants must have their type specified. - Scope:
constconstants can be declared in any scope, including the global scope.
Introducing Shadowing
Rust allows you to declare a new variable with the same name as a previous variable. This is called shadowing.
The new variable 'shadows' the old one, meaning any subsequent code will see the new variable's value. The old variable still exists in memory but cannot be accessed directly anymore.
fn main() {
let x = 5;
println!("First x: {}", x); // Outputs 5
let x = x + 1; // 'x' is shadowed by a new 'x'
println!("Second x: {}", x); // Outputs 6
{ // Inner scope
let x = x * 2; // 'x' is shadowed again
println!("Inner x: {}", x); // Outputs 12
}
println!("Outer x: {}", x); // Outputs 6 (inner x is out of scope)
}Shadowing for Type Conversion
One powerful use of shadowing is to transform a variable's value and even its type, while keeping the same name. This is common when you need to parse a string into a number.
Instead of creating a new variable name (e.g., string_val then num_val), you can reuse the same name.
fn main() {
let spaces = " ";
println!("Spaces string: '{}'", spaces);
// Shadow 'spaces' with a new variable that holds its length
let spaces = spaces.len();
println!("Spaces count: {}", spaces);
}Quick Check: Variables & Mutability
Consider the following Rust code. What will be the final value of y printed to the console?
Variables, Mutability, & Shadowing Recap
Great job! You've learned the essentials of variables in Rust:
- Use
letto declare variables, which are immutable by default. - Add
mutto make a variable mutable, allowing its value to change. - Use
constfor constants, which are always immutable and require type annotations. - Shadowing lets you declare a new variable with the same name, replacing the previous one. This is useful for type conversions.
Next, we'll dive into Rust's various primitive data types!
Frequently asked questions
Is the “Variables, Mutability, and Shadowing” lesson free?
Yes — the full text of “Variables, Mutability, and Shadowing” is free to read here on the web, and the Learn Rust Coding course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Variables, Mutability, and Shadowing”?
Understand how to declare variables, manage mutability, and use shadowing for flexible variable redefinition. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.
How long does the “Variables, Mutability, and Shadowing” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Variables, Mutability, and Shadowing
- Primitive Data Types and Operators
- Functions and Control Flow