3 ms·
It works when you access fields directly. Where I've seen people get frustrated is that calling a method on `&self` or `&mut self` is always a full borrow, eve
by CUViper 8y ago
It works when you access fields directly. Where I've seen people get frustrated is that calling a method on `&self` or `&mut self` is always a full borrow, even if it only really accesses and returns something partial. The borrow checker doesn't look to see what that method really uses in its implementation, just that the signature would allow full access.
- Filligree 8y agoThat's... understandable, perhaps. It would be difficult to implement something better, yes, but I'm also not sure it'd be better. In OO thinking, the question of which fields a method accesses should be an implementation detail, which shouldn't affect how the code calling it can look. If the borrow checker was smarter, then a change to a class implementation could break the code using it.
- CUViper 8y agoYeah, Rust usually eschews the sort of non-local reasoning that would require. It would be harder to implement, and harder for the programmer to think about too, especially with changes from afar as you say. Also, auto-`Deref` can make this even more surprising! If you have some `foo: Rc<Foo>`, then `&foo.bar` borrows the whole struct via `Rc::deref(&self)`. You can sometimes get around this by taking a full dereferenced borrow yourself -- `let foo: &Foo = &*foo;` -- and then work with partial borrows from that. Same goes for `DerefMut`, or really more so since `&mut` is exclusive.
- lmm 8y agoDid delegation ever make it into Rust? That would let you do a more comprehensible kind of partial borrowing: if you have impl TR for S { delegate * to self.f; } then calling TR methods should only require borrowing/owning f rather than the whole of self.
- oconnor663 8y agoThere aren't any new delegation features since 1.0 unfortunately. That said, if it worked this way, delegation would become part of a type's public API, such that changing the delegation details internally could break callers.