我试图从结构中使用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
关于rust - 结构的可变性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65162695/