Posts

Showing posts with the label Immutability

Shadowing Variables

Variable shadowing in Rust allows for the declaration of a new variable with the same name as an existing one, effectively masking the previous variable within its scope. Let's explore this powerful feature with examples. Understanding Shadowing In Rust, shadowing enables the creation of a new variable that hides the previous one within the same scope. This differs from mutability, as it involves redeclaring the variable with the let keyword. Consider the following example: fn main() { let planet = "Earth"; println!("The planet is: {}", planet); let planet = "Mars"; println!("The planet is: {}", planet); } Changing Data Types and Mutability Shadowing allows for flexibility in changing not only the value but also the data type and mutability of a variable. For instance: fn main() { let planet = "Earth"; println!("The planet is: {}", planet); let mut planet = 4; // Shadowing with a different d...