我正在尝试在 Rust 中实现循环链接数据结构。我Node
的 s 定义为:
#[derive(Debug)]
enum Node<'a> {
Link(&'a Node<'a>),
Leaf,
}
我正在尝试构建一个像这样的最小结构(额外的括号以获得更好的生命周期可见性):
fn main() {
let placeholder = Node::Leaf;
{
let link1 = Node::Link(&placeholder);
{
let link2 = Node::Link(&link1);
println!("{:?}", link2);
} // link2 gets dropped
} // link1 gets dropped
}
这可行,但现在我不知道如何将占位符替换link2
为“关闭循环”的引用。我试过这个,但它不起作用,因为我不能分配给link1
,这是借用了上面的行,并且因为link2
它仍然被引用时会超出范围link1
:
let placeholder = Node::Leaf;
{
let mut link1 = Node::Link(&placeholder);
{
let link2 = Node::Link(&link1);
link1 = Node::Link(&link2);
println!("{:?}", link2);
} // link2 gets dropped
} // link1 gets dropped
error: `link2` does not live long enough
--> src/main.rs:15:9
|
13 | link1 = Node::Link(&link2);
| ----- borrow occurs here
14 | println!("{:?}", link2);
15 | } // link2 gets dropped
| ^ `link2` dropped here while still borrowed
16 | } // link1 gets dropped
| - borrowed value needs to live until here
error[E0506]: cannot assign to `link1` because it is borrowed
--> src/main.rs:13:13
|
12 | let link2 = Node::Link(&link1);
| ----- borrow of `link1` occurs here
13 | link1 = Node::Link(&link2);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `link1` occurs here
我可以尝试通过使用Rc
s 来避免这些生命周期问题,但这听起来会破坏 Rust 的 0-runtime-cost 生命周期管理的目的。
另一种将所有节点放入 aVec
并仅直接引用该节点的尝试也不起作用:
use std::ops::IndexMut;
let mut store = Vec::new();
store.push(Node::Leaf);
store.push(Node::Link(&store[0]));
store.push(Node::Link(&store[1]));
*store.index_mut(1) = Node::Link(&store[2]);
因为我不能改变任何节点而不可变地借用它们,但它们都已经被不可变地借用了。
error[E0502]: cannot borrow `store` as immutable because it is also borrowed as mutable
--> src/main.rs:12:28
|
12 | store.push(Node::Link(&store[0]));
| ----- ^^^^^ - mutable borrow ends here
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
error[E0502]: cannot borrow `store` as mutable because it is also borrowed as immutable
--> src/main.rs:13:5
|
12 | store.push(Node::Link(&store[0]));
| ----- immutable borrow occurs here
13 | store.push(Node::Link(&store[1]));
| ^^^^^ mutable borrow occurs here
14 | *store.index_mut(1) = Node::Link(&store[2]);
15 | }
| - immutable borrow ends here
error[E0502]: cannot borrow `store` as immutable because it is also borrowed as mutable
--> src/main.rs:13:28
|
13 | store.push(Node::Link(&store[1]));
| ----- ^^^^^ - mutable borrow ends here
| | |
| | immutable borrow occurs here
| mutable borrow occurs here
error[E0502]: cannot borrow `store` as mutable because it is also borrowed as immutable
--> src/main.rs:14:6
|
12 | store.push(Node::Link(&store[0]));
| ----- immutable borrow occurs here
13 | store.push(Node::Link(&store[1]));
14 | *store.index_mut(1) = Node::Link(&store[2]);
| ^^^^^ mutable borrow occurs here
15 | }
| - immutable borrow ends here
有没有办法在没有运行时开销的情况下使用具有循环链接的这种结构,例如像我尝试过的纯引用?我对额外的内存成本很好,比如支持Vec
所有节点的所有权。