4 ms·
The one I run into most frequently: Passing field A mutably, and field B immutably, from the same struct to a function. The naive fix is, unfortunately, a clone
by the__alchemist 2y ago
The one I run into most frequently: Passing field A mutably, and field B immutably, from the same struct to a function. The naive fix is, unfortunately, a clone. There are usually other ways as well that result in verbosity.
- bionhoward 2y agoCould you change the function to accept the whole struct and make it mutate itself internally without external mutable references?
- the__alchemist 2y agoYes. Note that this requires a broader restructure that may make the function unusable in other contexts.
- Someone 2y agoAlso only if it is under your control. If it’s in the OS or a third-party library, you can’t change the API.
- pitaj 2y agoWhat? I think this just works... https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=2bfc3d7f7ed67244f25b077ad7555e0c https://play.rust-lang.org/?version=stable&mode=debug&editio...
- estebank 2y agoThe borrow checker is smart enough to track disjointed field borrows individually and detect that's fine, but if you have two methods that return borrows to a single field, there's no way of communicating to the compiler that it's not borrowing the entire struct. This is called "partial borrows", the syntax is not decided, and would likely only work on methods of the type itself and not traits (because trait analysis doesn't need to account for which impl you're looking at, and partial borrows would break that). The solution today is to either change the logic to keep the disjointed access in one method, provide a method that returns a tuple of sub-borrows, have a method that takes the fields as arguments, or use internal mutability.
- pitaj 2y agoAh, it wasn't clear from they they wrote that this is what they meant.
- duped 2y agoThe fix is destructuring
- pornel 2y agoThe problem is typically caused by &mut self methods exclusively borrowing all of self. I wish this not-a-proposal turned into a real proposal: https://smallcultfollowing.com/babysteps//blog/2021/11/05/view-types/ https://smallcultfollowing.com/babysteps//blog/2021/11/05/vi...