|
|
|
|
|
by yakcyll
3806 days ago
|
|
For a C++ developer, Rust introduces a lot of seemingly arbitrary rules and constraints on how data can be managed, moved around and referenced. In order to develop things that employ a lot of composing, one has to either make the code nigh unreadable with tons of unnecessary chaining (which is unavoidable, since 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!) or the entire data model has to be rethought with those rules in mind. Not sure about others, but I sure as hell still have a lot of trouble wrapping my head around boxes, mutability and lifetimes; maybe I'm making some fundamentally flawed assumptions trying to draw similarities between C++ and Rust, but those issues are showstoppers for me for now. |
|
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++.