[英]How to have multiple references for a single node in a tree structure using Rust
嘗試使用以下結構在 rust 中創建樹:
pub struct Node{
pub children: Vec<Box<Node>>,
pub parent: Option<Box<Node>>,
pub value: f32,
//.....
}
要構建一個新節點,請使用以下 function:
pub fn build_node(parent: Option<Box<Node>>)-> Node{
Node{
children: vec![],
parent,
value: 0.0,
}
}
嘗試添加節點時,例如:
let mut root_nd = tree::build_node(None, 5, state);
let mut next_nd = tree::build_node(Some(Box::new(root_nd)), 2);
root_nd.children.push(Box::new(next_nd));
會有錯誤,因為我正在借用例如root_nd
然后嘗試將next_nd
添加到root.children
列表中,即使沒有這個錯誤,我仍然需要在將next_nd
添加到root_nd
的孩子之后有一個參考. 我知道在 rust 中,同一元素不可能同時有多個可變引用。 所以問題是如何在 rust 中創建具有雙向引用的樹狀數據結構? 在我看來,這是一個沖突,因為 rust 不想要多個引用,但我需要樹中間的一個節點供他的父節點和他的子節點引用。
最近我一直在干預 Rust 中的樹木。 要使用 rust 中的樹,您將需要Rc
(單線程引用計數指針) ,以便您可以擁有多個所有權。 而且您還需要RefCell
來啟用內部可變性,因為編譯器不允許多個可變引用。 使用Rc
和RefCell
,您可以將TreeNode定義如下:
use std::rc::Rc;
use std::cell::RefCell;
pub struct TreeNode {
pub children: Vec<Rc<RefCell<TreeNode>>>,
pub parent: Option<Rc<RefCell<TreeNode>>>,
pub value: f32,
}
這是創建兩個相互引用的節點的一種方法:
impl TreeNode {
#[inline]
pub fn new(value: f32) -> Self {
TreeNode {
value,
children: vec![],
parent: None
}
}
}
let mut root_nd = Rc::new(RefCell::new(TreeNode::new(5.0)));
let mut child_nd = Rc::new(RefCell::new(TreeNode::new(2.0)));
child_nd.borrow_mut().parent = Some(root_nd.clone()); // use Rc::clone to create a new reference to root_nd
root_nd.borrow_mut().children.push(child_nd.clone());
由於我們使用Rc::clone
來創建對節點的新引用,因此root_nd
和child_nd
不會被消耗,並且仍然可以在以后的程序中訪問。
Rust 中的樹的更多示例:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.