In Rust, how does shadowing with `let port: u16 = port.parse()?;` differ from reassigning a `let mut port` binding?
answer
- two declarations, one name
- what each let introduces
- the type may change
- mut writes into the same variable
- E0384 and E0308 on assignment
basics
~20 sShadowing declares a brand-new variable that reuses the name, so port can go from &str to u16 and every binding stays immutable. Assigning to a let mut binding overwrites one variable, whose type never changes.
solid answer
~40 sEvery `let` introduces a new binding, and from that point the name refers to the newest one until it is shadowed again or its block ends. So `let port = port.trim(); let port: u16 = port.parse()?;` turns a `&str` into a `u16` under one name, and none of the bindings is mutable. Assignment is different: `port = ...` writes a new value into the existing variable, which needs `let mut` (otherwise E0384, "cannot assign twice to immutable variable") and must keep its declared type (otherwise E0308). A shadow declared in an inner block ends at its closing brace and the outer binding is visible again, and a closure or reference that captured the old binding keeps seeing the old value, because nothing was overwritten.
code
rust · 12 linesfn main() {
let limit = 10;
let within = |n: i32| n <= limit; // captures the first `limit`
let limit = 100; // a new binding; the closure still sees 10
println!("{} {}", within(50), limit);
let mut ports = Vec::new();
ports.push(443);
ports.push(80);
let ports = ports; // rebind without `mut`: frozen from here on
println!("{ports:?}");
}go deeper
Recall that a repeated let makes a new variable, so the type can change, while let mut lets you assign a new value of the same type.
Explain why the closure or reference made before a shadow still sees the old value, and name E0384 and E0308 as the two assignment errors.
Spot accidental shadowing in review, such as let total = total + x inside a loop body, and prefer the freeze idiom let v = v after setup.
Treat shadowing as a readability tool: one name per concept through a parse pipeline, mut only for values that genuinely evolve, and a review habit of asking which one each let is.
## Two ways to change what a name means Rust gives you two tools that look alike at a glance. **Shadowing** writes `let` again with a name that is already in scope; **mutation** declares the variable once with `let mut` and then assigns to it with `=`. They read similarly in a diff, but the compiler treats them as different operations, and the difference decides what type the name can have, whether the old value is still around, and which errors you get. ## Shadowing introduces a new variable The Reference defines a `let` statement as one that "introduces a new set of variables", visible "from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration". A second `let port` therefore does not touch the first `port`; it creates another variable and makes the name point at it. Consequences: - **The type may change.** `let port = port.trim();` is still `&str`, and `let port: u16 = port.parse()?;` is a `u16`. You keep one meaningful name instead of inventing `port_str` and `port_num`. - **Every step stays immutable.** None of the bindings needs `mut`, so after the last transformation the value cannot be changed by accident. - **The old value still exists.** It is simply unreachable by name. A value with a destructor is dropped at the end of its scope, in reverse order of declaration, not at the moment it is shadowed (unless it was moved into the new binding). - **Captures keep the old binding.** A closure or reference created before the shadow refers to the earlier variable. ```rust use std::num::ParseIntError; fn parse_port(port: &str) -> Result<u16, ParseIntError> { let port = port.trim(); // &str -> &str: a new binding let port: u16 = port.parse()?; // &str -> u16: another new binding Ok(port) } fn main() { let port = "8080"; { let port = 9000; // shadows only inside this block println!("inner: {port}"); } println!("outer: {port}"); println!("{:?}", parse_port(" 443 ")); println!("{:?}", parse_port("70000").is_err()); } ``` That program prints: ```plaintext inner: 9000 outer: 8080 Ok(443) true ``` The `?` on `port.parse()` returns early with the `ParseIntError` when the text is not a valid `u16`; `"70000"` is out of range, so that call returns `Err`. ## Mutation keeps one variable and one type `let mut` declares a single variable whose value you may overwrite. Two rules follow, and rustc enforces both: 1. **Without `mut`, a second assignment is an error.** `let port: u16 = 8080; port = 9000;` fails with E0384, "cannot assign twice to immutable variable `port`", and the compiler suggests adding `mut`. 2. **With `mut`, the type is fixed at declaration.** Assigning a `u16` to a variable declared from `"8080"` fails with E0308: ```plaintext error[E0308]: mismatched types --> e3.rs:3:12 | 2 | let mut port = "8080"; | ------ expected due to this value 3 | port = port.parse::<u16>().unwrap(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ expected `&str`, found `u16` ``` A third rule surprises people coming from the assignment side: calling a method that needs `&mut self` on a binding without `mut`, such as `ports.push(80)`, fails with E0596, "cannot borrow `ports` as mutable". Mutability belongs to the binding, not to the value. ## Where a shadow ends Shadowing follows block scope. A `let` inside `{ ... }` hides the outer name only until the closing brace; after it, the outer binding is the one the name refers to again. Mutation behaves the opposite way: an assignment inside an inner block changes the outer variable, and the change survives the block. | | Shadowing (`let` again) | Mutation (`let mut` + `=`) | |---|---|---| | What is created | a new variable | nothing; the existing one is written | | Type may change | yes | no (E0308) | | Needs `mut` | no | yes (E0384 without it) | | Old value | still alive until its scope ends | overwritten (and dropped) | | Inside an inner block | hides the outer name until `}` | changes the outer variable | | Earlier closures and borrows | still see the old value | a borrow blocks the write | ## Idioms and traps - **The parse pipeline.** `let port = port.trim(); let port: u16 = port.parse()?;` is the idiomatic way to refine an input step by step. - **Freezing after setup.** `let mut ports = Vec::new();` followed by pushes and then `let ports = ports;` moves the vector into an immutable binding, so later code cannot push to it. - **Accidental shadowing in a loop or branch.** Writing `let total = total + x;` inside a loop body creates a new `total` for that iteration only; the outer `total` never changes. When the intent is to accumulate, use `let mut total` outside and `total += x` inside. - **Shadowing is not a move by itself.** `let port = port.trim();` borrows from the old `port`, which must therefore stay alive; nothing is copied or freed. In review, ask one question of every repeated `let`: is this a new value derived from the old one (shadow it), or the same variable evolving over time (make it `mut`)?
- In Rust, after `let limit = 10; let within = |n: i32| n <= limit; let limit = 100;`, what does `within(50)` return?`false`. The closure captured the first `limit` binding, whose value is 10. The later `let limit = 100;` creates a separate variable and does not touch the captured one, so the closure still tests `50 <= 10`. With `let mut limit` and an assignment `limit = 100;` instead, the program would not compile, because the closure holds a shared borrow of `limit` while you try to write it.
- In Rust, why would you write `let ports = ports;` after filling a `let mut ports` vector?It rebinds the vector to an immutable name, ending the mutable phase: any later `ports.push(...)` fails with E0596, "cannot borrow `ports` as mutable". The value moves into the new binding, so no elements are copied. It documents that setup is finished and lets the compiler hold you to it.
- Shadowing overwrites the original variable in place, like an assignment.
- A shadowed value is dropped the moment the new binding appears.
- A `let mut` variable can later be assigned a value of another type.
- Shadowing requires the first binding to be declared `mut`.
- A shadow declared inside an inner block stays in effect after the block ends.