结构中的可变性

Mutability in a struct

我正在尝试从结构中使用 BTreeMap(或 HashMap),但我不能,因为它一直抱怨所有权问题。

cannot move out of `self.vertices` which is behind a shared reference
move occurs because `self.vertices` has type `std::collections::BTreeMap<u32, std::vec::Vec<u32>>`, which does not implement the `Copy` trait
help: consider borrowing here: `&self.vertices`rustc(E0507)
digraph.rs(13, 17): move occurs because `self.vertices` has type `std::collections::BTreeMap<u32, std::vec::Vec<u32>>`, which does not implement the `Copy`

现阶段我完全糊涂了。

use std::collections::BTreeMap;

pub struct DirectedGraph {
    vertices: BTreeMap<u32, Vec<u32>>
}

impl DirectedGraph {
    pub fn new() -> DirectedGraph {
        DirectedGraph { vertices: BTreeMap::new() }
    }

    pub fn add_edge(&self, vertex: u32, edge: u32) {
        let v = &self.vertices;
        v.entry(vertex).or_insert(vec!()).push(edge);
    }

    pub fn num_vertices(&self) -> usize {
        self.vertices.len()
    }
}
error[E0596]: cannot borrow `*v` as mutable, as it is behind a `&` reference
  --> src\digraph.rs:14:9
   |
13 |         let v =&self.vertices;
   |                -------------- help: consider changing this to be a mutable reference: `&mut self.vertices`
14 |         v.entry(vertex).or_insert(vec!()).push(edge);
   |         ^ `v` is a `&` reference, so the data it refers to cannot be borrowed as mutable

error: aborting due to previous error
For more information about this error, try `rustc --explain E0596`.

问题似乎是您正在尝试改变您尚未标记为可变的内容。 add_edge 方法显然必须改变结构,但你有一个 &self 接收器而不是 &mut self。进行更改后,代码编译:

use std::collections::BTreeMap;

pub struct DirectedGraph {
    vertices: BTreeMap<u32, Vec<u32>>
}

impl DirectedGraph {
    pub fn new() -> DirectedGraph {
        DirectedGraph { vertices: BTreeMap::new() }
    }

    pub fn add_edge(&mut self, vertex: u32, edge: u32) {
        self.vertices
            .entry(vertex)
            .or_insert(Vec::new())
            .push(edge);
    }

    pub fn num_vertices(&self) -> usize {
        self.vertices.len()
    }
}

playground