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
Published 4 years ago
Updated 3 years ago

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.

Stephen James
Stephen James
~ 4 years ago

The solution I found for this was to add let to line 9 using shadowing. This came from the page linked to in the hint.

mi-skam .
mi-skam .
~ 4 years ago

You don't even need block scope to shadow the variables, it works in the same scope simply by using let number = "something", which blends in the new value.

Anthony Albertorio
Anthony Albertorio
~ 4 years ago

According to the docs we can use let again aka "shadowing" within the same scope to re-assign the variable. This removes the need for the extra curly braces and scope.

By using let, we can perform a few transformations on a value but have the variable be immutable after those transformations have been completed. The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name.

fn main() {
    let number = "3"; // don't change this line
    println!("Number {}", number);
    let number = 3; // shadow the variable number, add let
    println!("Number {}", number);
}

Hope this helps.

Markdown supported.
Become a member to join the discussionEnroll Today