rust - 结构的可变性

标签 rust reference borrow-checker borrowing mutability

我试图从结构中使用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/

相关文章:

types - 在导出的签名中隐藏私有(private)类型

rust - #[cfg(test)] 放在 lib.rs 的顶部时会做什么?

c++ - 返回 std::string 作为 const 引用

rust - 与(表面上)似乎完全安全的短暂生命周期值相混淆

rust - Rust 可以捕获 C/C++ 库的 stdout/stderr 吗?

parallel-processing - 是否可以将 Rayon 和 Faster 结合起来?

python - 为什么当我在 python 的函数中修改它时列表没有改变

c++ - 如何将函数引用传递给参数

rust - 如何在 Rust 中实现获取缓存或加载操作?

rust - 我可以用借用的元素来改变向量吗?