How to use Rc and Hashmap?

I'd like to share a hashmap using Rc.

My code:

    let mut hm: HashMap<String, String> = HashMap::new();

    let rc_hm = Rc::new(hm);
    let rc_hm_cloned = rc_hm.clone();
    let mut borrow_hm = rc_hm_cloned.borrow();


15 |     let mut borrow_hm = rc_hm_cloned.borrow();
   |                         -------------^^^^^^--
   |                         |            |
   |                         |            cannot infer type for struct `std::rc::Rc<std::collections::HashMap<std::string::String, std::string::String>>`
   |                         this method call resolves to `&Borrowed`
   = note: cannot satisfy `std::rc::Rc<std::collections::HashMap<std::string::String, std::string::String>>: std::borrow::Borrow<_>`

Playground -- CLICK ME!

Rc<HashMap> makes it read-only. You need Rc<RefCell<HashMap>> to have it mutable.

1 Like

@kornel Same effect. ;(

Your import of std::borrow::Borrow is getting in the way, because then it tries to use Borrow::borrow directly on the Rc. What you want is really RefCell::borrow, an inherent method unrelated to Borrow, which you can usually get through implicit auto-deref.

Also, you want borrow_mut() if you intend to mutate through this.
(But similarly, watch out for BorrowMut getting in the way.)

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.