1. 6
    Rustlings variables5: Using block scopes to shadow previously declared variables
    1m 25s

Rustlings variables5: Using block scopes to shadow previously declared variables

Chris Biscardi
InstructorChris Biscardi
Share this video with your friends

Social Share Links

Send Tweet

README for this exercise

Chris Biscardi: [0:00] In variables5, we have a main() function. The body of the main() function sets a number = "3", a println! Macro that prints out the number. We reset the number to 3, an integer, then we use a println! Macro to print the number again.

[0:20] In this case, Rust has told us we have mismatched types. When we add that number to 3, the integer, Rust expects a '&str' and it finds the integer. We know that we can put a mutable keyword here to let us set the number to a different value. That doesn't really help us though because we still have the same error.

[0:42] Let's take a hint-lings. I'll let you read this on your own. Basically, it says exactly said wherein variables 3, we use the mut keyword. That doesn't help us here because we're converting between two different types.

[0:57] The change that we need, as the hint has given us, is shadowing. This lets us take one variable that's in scope and create a new scope inside of which we can re-declare that name and use it with a different value. The Number name inside of this block lives with the length of this block while this number lives with the length of the entire program.