Re:Gnirehtet rewritten in Rust
by viraptor on Sunday September 24, 2017 @06:03PM
(#15326726)
I think in the encapsulation / content example they missed the possibility of creating an explicit block on your own. I believe something like this would solve it:
Since the sum value itself doesn't borrow anymore.
[ Parent
| on HN ]
Yes, you're right, this particular (artificial) example could be rewritten easily so that it compiles.
But the point was to show that a compiling program may not compile anymore after factoring some code into a private method.
It's a useful lesson in that Rust's correctness relies on certain notions of borrowing dependencies which don't necessarily match what you assume. Especially that the lifecycle dependency across a function call is essentially opaque to the compiler.
Which is how it has to be, or you could never state anything sane about the lifecycle when you return a reference.
Is the purpose of encapsulation to wrap all data fields in functions offering mutable references to data? I thought it was the exact opposite.
The purpose was to show that something lifetime-bound to a part of a struct becomes lifetime-bound to the whole struct when returned from a function.
Using mutable references is the minimal way to get this.