1

我正在尝试在 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

我可以尝试通过使用Rcs 来避免这些生命周期问题,但这听起来会破坏 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所有节点的所有权。

4

1 回答 1

3

有没有办法在没有运行时开销的情况下使用具有循环链接的这种结构,例如像我尝试过的纯引用?我对额外的内存成本很好,比如支持 Vec 持有所有节点的所有权。

是的,有很多方法。

然而,重要的是要意识到 Rust 需要始终执行Aliasing XOR Mutability原则。最好在编译时强制执行它,以使运行时成本为 0,但是有时需要在运行时对其进行管理,并且为此有多种结构:

  • Cell, RefCell, AtomicXXX, Mutex, RWLock(名字不好的)是关于安全地改变别名项目,
  • Rc, Weak, Arc, 是关于拥有多个所有者的。

与获得的灵活性相比,平衡潜在的运行时开销是一门艺术。这需要一些经验和实验。


在您的特定情况下(使用相互引用的节点构建 BNF 语法),我们确实可以使用Cell可变性实现 0 运行时开销。

然而,主要困难是获得一组具有相同生命周期的节点。您在 a 的想法上走在正确的轨道上Vec<Node>,但是当您注意到一旦借用一个节点就不能再改变 a Vec:这是因为增长Vec可能会导致它重新分配其底层存储,这将呈现已经获得的参考悬空(指向释放的内存)。

通用的解决方案是使用不安全的代码自己管理节点的生命周期。但是,您很幸运:正如您所提到的,您的情况很特殊,因为节点的数量是有界的(受语法定义),并且您一次将它们全部删除。这需要一个竞技场

因此,我的建议是双重的:

  1. 在 a 中存储节点typed-arena
  2. 用于Cell可变部分 ( &Tis Copy)。

如果没有代码,您将无法将 arena 存储在与语法的其余部分相同的结构中unsafe;是否使用unsafe或构建程序由您决定,以使竞技场比计算更有效。

于 2017-05-07T10:29:01.403 回答