<分区>
我想对一个非常大(节点数)的图建模,该图由许多非常大(内存方面)的节点组成。由于节点如此之大,我只想将它们存储一次并将借用传递给它们,所以在概念上是这样的:
struct Graph<'a> {
nodes: Vec<Node<'a>>,
}
struct Node<'a> {
edges: HashMap<String, &'a Node>,
// ...lots of other data...
}
当然没有办法像这样构造一个Graph
因为(a)Vec
不允许我在元素借用时添加新节点, (b) 我不能告诉 rustc nodes
向量将在 'a
的生命周期内存在。我也不能使用像 Rc
这样的东西,因为图形有循环。
我希望能够表达的是某种竞技场,它让我可以分配很多 Node
,只要竞技场存在,就向它们进行不可变借用,并使用生命周期检查以确保在取消分配竞技场时我没有剩余的 Node
引用。像这样的东西:
struct Graph<'a> {
nodes: Arena<'a, Node<'a>>,
}
struct Node<'a> {
edges: HashMap<String, &'a Node>,
}
impl<'a, A> Arena<'a, A> {
fn own(&self, a: A) -> &'a A {
// magic
}
}
impl<'a, A> Drop for Arena<'a, A> {
fn drop(&'a mut self) {
// magic
}
}
这在语义上可以用 Rust 表达吗?