【发布时间】:2021-09-17 13:35:44
【问题描述】:
我试图通过让每个节点存储对其邻居的引用来实现图形结构。具体来说,我正在尝试创建一个网格,其中每个节点最多可以引用 4 个邻居 - 就像一个“二维链表”。
但我在分配引用时遇到错误。这个简约的例子重现了我的问题:
#[derive(Clone)]
struct Node<'a> {
neighbor: Option<&'a Node<'a>>, // optional reference to another Node
}
fn main() {
// a bunch of nodes:
let mut nodes: Vec<Node> = vec![ Node{neighbor: None}; 100];
// I want node 0 to have a reference to node 1
nodes[0].neighbor = Some(&nodes[1]);
}
产生以下错误:
error[E0502]: cannot borrow `nodes` as mutable because it is also borrowed as immutable
--> src/main.rs:12:5
|
12 | nodes[0].neighbor = Some(&nodes[1]);
| ^^^^^------------------------------
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
| immutable borrow later used here
error: aborting due to previous error
For more information about this error, try `rustc --explain E0502`.
我正在努力弄清楚这应该如何在 Rust 中完成。我应该改用指针吗?
【问题讨论】:
-
为什么不存储索引而不是节点本身的引用?
-
我希望能够使程序的其余部分独立于用于实例化节点的结构。但也许这在 Rust 中是个坏主意?
-
你绝对可以这样做,只是索引也很简单。你可能想看看
Rc。 -
GhostCell 可能会为您提供帮助,它正是为此目的而制作的。 Here's a github repo with some collections using it 和 here's a reddit post about a 1d linked list
-
...如果没有任何安全方法适合您(人体工程学、性能等),您可以随时使用不安全的块和原始指针
标签: rust borrow-checker