Hacker News new | ask | show | jobs
by geofft 3796 days ago
simple dereferencing and assigning a value of a field in a structure to a variable means the structure is now borrowed and you can't reference the field nor the structure until the variable goes out of scope; please, for the love of all that is holy, prove me wrong!

This is only partially true. If you hold a mutable reference to a field in a structure, you can't get a reference to the entire structure. (Think of a mutable reference as a read-write lock, because that's what it is, just at compile time / type level instead of at runtime.) However, you can get a mutable reference to other fields in the structure. And an immutable reference to a field (analogous to a read-only / shared lock) does not prevent other immutable references, so you can totally get a reference to the structure while a reference to one of its fields is outstanding.

Here's an example of this on play.rust-lang.org: http://is.gd/ySSsex

That compiles and runs with the extra scope around the mutable borrows. If you comment out that scope, then yes, it won't compile.

My experience, coming to Rust from C++ and C, is that a lot of real-world C++ and C code is imprecise about mutability and shared references, and relies on the programmer not doing anything particularly weird. It's true that in this example, nothing would go wrong by omitting the braces because the references g and h aren't actually used. But in larger and legacy codebases, it's very easy to forget the mutability rules that were in the head of the previous programmer. So directly porting C++ code is going to be annoying, but that's mostly because the hard work is figuring out what was implicit in the C++.