Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is all true in this instance, but it doesn't have to be at all. You could write something like the following:

    let name = "Arthur".to_owned();
    //... Do something with &Arthur

    let name = "Bethan".to_owned();
    //... Do something with &Bethan
In this situation, ownership of the first string was never passed on, and the value will be dropped (deallocated, destructed, etc) at the end of the scope, meaning that also in Rust, the first string value is shadowed and becomes inaccessible, much like in your description of C++. In addition, because in this case both variables have the same type, you can use second variable thinking that you're using the first one, and the compiler will not help you, you'll just end up using the wrong name somewhere.

Fwiw, I find this feature very useful, and it's helpful more often than it is a nuisance. But there are no guarantees that you're consuming or transforming the object you're shadowing, and the compiler won't necessarily help you out if you simply accidentally use the same name twice.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: