Shadowing -

We have some extra information here. We aren't supposed to change line 7, but we are somehow expected how to make things work. If we look at the error message above, we can see that we have set the number variable to a string and then we are attempting to change it to an integer of some sort. It won't let us.

Our first instinct takes us back to our previous discussion on mutability.  And so one's first instinct might be to add a mut to line 7, ignoring the instructions to leave that line alone. We also aren't allowed to rename the variable on line 9. Gross.

We can break the rules if we want to. There's no Rust Police. Go ahead and stick that mut in on line 7.

Bad news, that doesn't change anything. If we look closely, the error isn't about how we havent made the variable mutable, it's about types. And this is the opportunity that we are going to use to talk about shadowing.

Shadowing is what occurs in Rust when a new variable is declared with the same name as an old variable in the same scope. This new variable "shadows" the old one, hiding it from the program.

As a Rubyist you may be like, "How is this not reassignment?" Technically it's not. Spiritually, it is. Reassignment is what happens when a new value is assigned to an existing variable. But that's not what is happening in this case, because variables are immutable by default. What we are doing with shadowing is creating a NEW variable with the same name, and you're effectively replacing it. This is safer.

It looks like this.

Subscribe to Rust for Rubyists

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.