Replies: 1 comment 1 reply
-
|
Hi @humb1t, thanks for trying out the library! I'm glad you noticed this limitation with mutable implicit arguments. It is something I didn't go into in the blog post and tutorials, so as not to overwhelm readers with too much information all at once. The short answer is exactly as you suspect. A key limitation of trait-based abstractions in Rust is that the entire A proper solution would require Rust to implement more refined borrow checking through Polonius or view types, which would allow the borrow checker to understand that two mutable borrows do not overlap. CGP also has more advanced techniques to split a However, even with those workarounds, dealing with The most reliable way to avoid this in practice is to wrap mutable fields in That said, if you can confine the mutability to a very small scope, it is still possible to access more than one mutable field through CGP. The key is to use #[cgp_auto_getter]
pub trait HasMutableStates {
fn accounts(&mut self) -> &mut HashMap<ClientId, Account>;
fn transactions(&mut self) -> &mut HashMap<(ClientId, TransactionId), Difference>;
fn disputed_transactions(&mut self) -> &mut HashMap<(ClientId, TransactionId), Difference>;
}
#[cgp_fn]
#[uses(HasMutableStates)]
pub fn update_state(&mut self) {
self.accounts().get_mut(&ClientId(1)).unwrap().last_active = Instant::now();
self.transactions().insert((ClientId(1), TransactionId(1)), Difference(100));
}Each call to a mutable getter is completed before the next one begins, so the borrow checker is satisfied. The moment you try to hold two of those references alive at the same time, you are back in the territory where |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi and big thanks for this library. It is really refreshing to see such projects driving Rust language into the bright future.
When playing with
#[cgp_fn]and#[implicit]I found that it will not work with several mutable references:which is quit logical, as it is unclear how to get mutable references from all of the fields of struct like below at the same time without violating basis of rust borrowing system:
meanwhile, the question stays in my head. If I have different Contexts, that I want to abstract over in function, how can I combine
#[cgp_fn]with mutable references. Maybe there is already a good example that I failed to find or ideas how to do it "idiomatically" in CGP? Thank you in advance, I will be glad to read your thoughts.Beta Was this translation helpful? Give feedback.
All reactions