Skip to content

Instantly share code, notes, and snippets.

@hadronized
Last active November 4, 2016 14:48
Show Gist options
  • Save hadronized/a614831b233b00b47167cdbed21ac07d to your computer and use it in GitHub Desktop.
Save hadronized/a614831b233b00b47167cdbed21ac07d to your computer and use it in GitHub Desktop.
// The problem arises as I have the following type representing a cache
struct Cache {
foo_data: Vec<Foo>,
bar_data: Vec<Bar>,
// ...
}
// So, there’s a function called get_by_id() that basically takes an index into a one of the Vec<T> above and returns an Option<&T>.
// Though, because of resource dependency, that function takes a mutable Cache so that, in a trait implementation for each type,
// you can ask for a load of another resource in the cache:
impl Cache {
// ...
fn get_by_id(&mut self, id: u32) -> Result<…, …>
}
// The problem is that when implementing that function for a wrapper type over Cache, I try to have two &mut:
struct Zoo { … }; // it has a Cache
impl Zoo {
fn get_by_id(&mut self, id: u32) -> Result<…, …> {
// ...
// imagine we need to resynchronize the resource here
if let Ok(data) = self.foo_data.get_mut(id) {
// ok, the resource is already in the cache; though here, we’ve locked &mut self line 26
// ...
reload(&data.something, self); // error: cannot borrow because already borrowed!
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment