DEV Community

Discussion on: My first impressions of Rust

tensorprogramming profile image
Tensor-Programming • Edited on

Shadowing is a bit of a misunderstood feature in rust. It came from ocaml which is the language rust was originally built on top of. You mention that shadowing is like mutation but it really isn't. Shadowing is not mutation because a shadowed let expression isn't an assignment. Each let binding binds a new value and it's irrelevant as to whether or not that variable name is the same as another one. In other words, the original immutable value can still exist especially when we are talking about multiple scopes (from functions and closures etc) while another value is shadowing it. It's sort of like how closures can freeze an environment and it starts to make more sense when you consider move semantics and stuff like that. Just as with any other immutable value, rather then change the value you replace it a different one.

Perhaps this is a feature that can be abused and used to generate bad habits but its not nearly as bad as you make it sound. Anyhow, you should look into it a bit more and consider the potential use cases (both good and bad). Even in inexperienced hands it's not that big of a deal.

I agree with most of your assessment though. I have taught rust for almost 3 years now, it's very easy to see the pros and the cons of the language especially when stacked against something like go. I like rust and I also like go, but when it comes to building something quickly, I'll choose go 9 times out of 10. Either way both are great tools to have in your programmer toolbelt. They are languages that will continue to define the future of the discipline going forward.

deepu105 profile image
Deepu K Sasidharan Author

Hi thanks for the detailed response. As I said I do understand the reasoning behind it and I have no problems with shadowing in different scopes, my problem, as mentioned in post, is with shadowing in the same scope. I see more cons than pro in that case. Yes its not exactly mutation in theoritcal sense but can achieve the same result of accidental mutation with this.

l0uisc profile image
Louis Cloete

Shadowing is most useful when you are parsing keyboard input:

use std::io;

let mut num = String::new()
io::stdin().read_line(&mut num).expect("Failed to read line");
let num: usize = num.trim().parse().expect("Failed to parse number");
// Continue to use num as immutable usize. The mutable String is now not accessible any more.