4 ms·
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
by viraptor 9y ago
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:
let new_sum = { calculate it from self.content() }
self.sum = new_sum;
Since the sum value itself doesn't borrow anymore.
- rom1v 9y agoYes, 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.
- mathw 9y agoIt'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.
- fnord123 9y agoIs the purpose of encapsulation to wrap all data fields in functions offering mutable references to data? I thought it was the exact opposite.
- rom1v 9y agoThe 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.