【发布时间】:2020-01-11 10:42:31
【问题描述】:
我正在尝试使用以下类型在 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 似乎是可变借用。是否可以构建我想要的内存布局?如果有,怎么做?
【问题讨论】:
-
你不能那样做。使用
Vec<Rc<RefCell<Node>>> -
@FrenchBoiethios - 谢谢 - 作为
Graph类型还是edges类型?还是他们都应该有那种类型? -
如果不去
RefCell,我认为这会失去我想要的 Rust 的安全保证? -
@NeilMitchell
RefCell不会失去安全保证,但确实会将它们从编译时转移到运行时。
标签: rust borrow-checker