不能借用不可变借来的内容作为可变性

dmg*_*vil 21 rust

我正在尝试开发一个消息路由应用程序.我已经阅读了正式的Rust文档和一些文章,并认为我得到了指针,拥有和借用的东西如何工作,但意识到我没有.

use std::collections::HashMap;
use std::vec::Vec;

struct Component {
    address: &'static str,
    available_workers: i32,
    lang: i32
}

struct Components {
    data: HashMap<i32, Vec<Component>>
}

impl Components {
    fn new() -> Components {
        Components {data: HashMap::new() }
    }

    fn addOrUpdate(&mut self, component: Component) -> &Components {
        if !self.data.contains_key(&component.lang) {

            self.data.insert(component.lang, vec![component]);
        } else {
            let mut q = self.data.get(&component.lang); // this extra line is required because of the error: borrowed value does not live long enough
            let mut queue = q.as_mut().unwrap();
            queue.remove(0);
            queue.push(component);
        }
        self
    }

}
Run Code Online (Sandbox Code Playgroud)

(也可在操场上使用)

产生错误:

error: cannot borrow immutable borrowed content `**queue` as mutable
  --> src/main.rs:26:13
   |
26 |             queue.remove(0);
   |             ^^^^^ cannot borrow as mutable

error: cannot borrow immutable borrowed content `**queue` as mutable
  --> src/main.rs:27:13
   |
27 |             queue.push(component);
   |             ^^^^^ cannot borrow as mutable
Run Code Online (Sandbox Code Playgroud)

你能否解释一下这个错误,如果你能给我正确的实施,那就太棒了.

She*_*ter 32

以下是您的问题的MCVE:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在NLL之前

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

在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
Run Code Online (Sandbox Code Playgroud)

很多时候,当这样的事情看起来令人惊讶时,打印出所涉及的类型是有用的.让我们打印出以下类型queue:

let mut queue: () = q.as_mut().unwrap();
Run Code Online (Sandbox Code Playgroud)
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>`
Run Code Online (Sandbox Code Playgroud)

我们有一个对a 的不可变引用的可变引用.因为我们有一个不可变的引用,我们无法修改它!更改为更改类型和代码编译.Vec<u8>Vecself.data.getself.data.get_mut&mut &mut collections::vec::Vec<u8>


如果要实现"插入或更新"的概念,则应检查entryAPI,这样更高效,更简洁.

除此之外,Rust snake_case用于方法命名,而不是camelCase.