How to use Rc and Hashmap?

Hello.
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();

Error:

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.

Rc::new(RefCell::new(hm))
1 Like

@kornel Same effect. ;(

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=1ad503f6c3ac29abb5038f22fc5a1b8f

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.