How can I borrow from a HashMap to read and write at the same time?

前端 未结 2 934
旧时难觅i
旧时难觅i 2020-12-02 02:42

I have a function f that accepts two references, one mut and one not mut. I have values for f inside a HashMap

2条回答
  •  佛祖请我去吃肉
    2020-12-02 03:07

    Something appears to have changed since the question was asked. In Rust 1.38.0 (possibly earlier), the following compiles and works:

    use std::collections::HashMap;
    
    fn f(a: &i32, b: &mut i32) {}
    
    fn main() {
        let mut map = HashMap::new();
    
        map.insert("1", 1);
        map.insert("2", 2);
    
        let a: &i32 = map.get("1").unwrap();
        println!("a: {}", a);
    
        let b: &mut i32 = map.get_mut("2").unwrap();
        println!("b: {}", b);
        *b = 5;
    
        println!("Results: {:?}", map)
    }
    

    playground

    There is no need for RefCell, nor is there even a need for the inner scope.

提交回复
热议问题