Arc::get_mut doesn't work with multiple references

The following will panick at the let _y = ... line:

use std::sync::Arc;

fn main() {
    let mut o = Arc::new(10);
    let _x = o.clone();
    let _y = Arc::get_mut(&mut o).unwrap();
}

I used to have a fn f(&mut self), but because Arc::get_mut only works if there are less than 2 references to the Arc pointer, I had to use RwLock for the fields I want to mutate. So I got this field, m_assets:

pub struct Ftl {
    // ...
    m_assets: Arc<RwLock<HashMap<Locale, Arc<fluent::FluentBundle<fluent::FluentResource>>>>>,
    // ...
}

The problem with that is that then I get an error among these lines:

if self.m_assets_clean_unused {
    self.m_assets.read().unwrap().clear();
}

cannot borrow data in an Arc as mutable
trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<RwLock<HashMap<icu::icu_locid::Locale, Arc<FluentBundle<FluentResource, intl_memoizer::IntlLangMemoizer>>>>>rustc Click for full compiler diagnostic

cannot borrow data in an Arc as mutable
trait DerefMut is required to modify through a dereference, but it is not implemented for Arc<RwLock<HashMap<icu::icu_locid::Locale, Arc<FluentBundle<FluentResource, intl_memoizer::IntlLangMemoizer>>>>>rustc Click for full compiler diagnostic

I tried a variety of things.

.clear() modifies the map. It should be

self.m_assets.write().unwrap().clear();
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.