Cannot borrow immutable borrowed content as mutable

后端 未结 1 459
暗喜
暗喜 2020-12-06 04:30

I\'m trying to develop a message routing app. I\'ve read the official Rust docs and some articles and thought that I got how pointers, owning, and borrowing stuff works but

相关标签:
1条回答
  • 2020-12-06 05:25

    Here is an MCVE of your problem:

    use std::collections::HashMap;
    
    struct Components {
        data: HashMap<u8, Vec<u8>>,
    }
    
    impl Components {
        fn add_or_update(&mut self, component: u8) {
            let mut q = self.data.get(&component);
            let mut queue = q.as_mut().unwrap();
            queue.remove(0);
        }
    }
    

    Before NLL

    error[E0596]: cannot borrow immutable borrowed content `**queue` as mutable
      --> src/lib.rs:11:9
       |
    11 |         queue.remove(0);
       |         ^^^^^ cannot borrow as mutable
    

    After NLL

    error[E0596]: cannot borrow `**queue` as mutable, as it is behind a `&` reference
      --> src/lib.rs:11:9
       |
    11 |         queue.remove(0);
       |         ^^^^^ cannot borrow as mutable
    

    Many times, when something seems surprising like this, it's useful to print out the types involved. Let's print out the type of queue:

    let mut queue: () = q.as_mut().unwrap();
    
    error[E0308]: mismatched types
      --> src/lib.rs:10:29
       |
    10 |         let mut queue: () = q.as_mut().unwrap();
       |                             ^^^^^^^^^^^^^^^^^^^ expected (), found mutable reference
       |
       = note: expected type `()`
                  found type `&mut &std::vec::Vec<u8>`
    

    We have a mutable reference to an immutable reference to a Vec<u8>. Because we have an immutable reference to the Vec, we cannot modify it! Changing self.data.get to self.data.get_mut changes the type to &mut &mut collections::vec::Vec<u8> and the code compiles.


    If you want to implement the concept of "insert or update", you should check into the entry API, which is more efficient and concise.

    Beyond that, Rust uses snake_case for method naming, not camelCase.

    0 讨论(0)
提交回复
热议问题