<分区>
我正在尝试使用以下类型在 Rust 中表示图形:
struct Node<'a> {
edges: Vec<&'a Node<'a>>,
}
type Graph<'a> = Vec<Node<'a>>;
Graph
的约束是所有节点都指向同一向量中的其他节点。我可以创建一个单例图:
fn createSingleton<'a>() -> Graph<'a> {
let mut items: Graph<'a> = Vec::new();
items.push(Node { edges: Vec::new() });
return items;
}
但是当我尝试创建一个有两个节点的图时,其中一个指向另一个:
fn createLink<'a>() -> Graph<'a> {
let mut items: Graph<'a> = Vec::new();
items.push(Node { edges: Vec::new() });
items.push(Node { edges: vec![&items[0]] });
return items;
}
我得到一个错误:
cannot borrow `items` as mutable because it is also borrowed as immutable
特别是 &items[0]
是一个不可变的借用,而第二个 items.push
似乎是一个可变的借用。是否可以构建我想要的内存布局?如果是,怎么办?