I simply don't see enough shadowing where there's confusion in real Rust code to make it worth the syntatic change. There's plenty of code I work with that contains shadowing, but in practice, it's confined to two cases:
- Inside an inner scope (e.g. a loop body) where the thing being shadowed from the outer scope isn't needed in the inner scope. It lets you have a clearer name in each scope without significant confusion.
- Within the same scope, when you're taking the same logical thing and changing its type - why should I need a different name for a CLI argument as an
&OsStr and for it as f64 (the real type after parsing)?
For the first, this is things like:
let mut shadow = input.my_shadow();
// do things with shadow
let other_device_count = input
.other_device_shadows()
.into_iter()
.filter(|shadow| shadow.is_valid())
.count();
if other_device_count > MAX_DEVICES {
shadow.set_overload();
} else if other_device_count == 0 {
shadow.set_missing();
} else {
shadow.set_normal();
}
Here, I've got a shadowing inside the closure - instead of shadow inside the closure representing the thing outside the closure parameters, it represents the thing inside the closure parameters. This shadowing is fine, because it makes semantic sense, and it's very clear what's going on.
For the second, it's things like
let timeout = std::env::var("TIMEOUT_MS").or_else(|e| match e {
std::env::VarError::NotPresent => Ok(String::from(DEFAULT_TIMEOUT_MS)),
std::env::VarError::NotUnicode(_) => Err(Error::TimeoutMustBeNumeric),
})?;
let timeout: u64 = timeout.parse().map_err(|_| Error::InvalidTimeout)?;
let timeout = Duration::from_millis(timeout);
where someone has decided that it's clearer to keep shadowing the previous name with a new type than it is to write this as:
let timeout = Duration::from_millis(
std::env::var("TIMEOUT_MS")
.or_else(|e| match e {
std::env::VarError::NotPresent => Ok(String::from(DEFAULT_TIMEOUT_MS)),
std::env::VarError::NotUnicode(_) => Err(Error::TimeoutMustBeNumeric),
})?
.parse::<u64>()
.map_err(|_| Error::InvalidTimeout)?,
);
In this specific case, the second form is also readable, but it gets more complex when there's validation logic between reading the string and parsing it into the final form, and you're trying to not even attempt to parse into the final form if you can detect and clearly error on an incorrect format.