[英]Rust borrowed pointers and lifetimes
在我的代碼中,我有一個相互遞歸的樹結構,看起來像下面的樣子:
enum Child<'r> {
A(&'r Node<'r>),
B,
C
}
struct Node<'r> {
children : [&'r Child<'r>,..25]
}
impl <'r>Node<'r> {
fn new() -> Node {
Node {
children : [&B,..25]
}
}
}
但它不能按原樣編譯。 進行修改的最佳方法是什么?
這是一個可以從樹外修改節點的版本,我想這就是要求的版本。
use std::rc::Rc;
use std::cell::RefCell;
struct Node {
a : Option<Rc<RefCell<Node>>>,
b : Option<Rc<RefCell<Node>>>,
value: int
}
impl Node {
fn new(value: int) -> Rc<RefCell<Node>> {
let node = Node {
a: None,
b: None,
value: value
};
Rc::new(RefCell::new(node))
}
}
fn main() {
let first = Node::new(0);
let second = Node::new(0);
let third = Node::new(0);
first.borrow_mut().a = Some(second.clone());
second.borrow_mut().a = Some(third.clone());
second.borrow_mut().value = 1;
third.borrow_mut().value = 2;
println!("Value of second: {}", first.borrow().a.get_ref().borrow().value);
println!("Value of third: {}", first.borrow().a.get_ref().borrow().a.get_ref().borrow().value);
}
Rc
是引用計數的指針,並允許單個對象具有多個所有者。 但是,它不允許突變,因此需要RefCell
,它允許運行時檢查可變借用。 這就是代碼使用Rc<RefCell<Node>>
。 Option類型用於通過Option<Rc<RefCell<Node>>>
表示潛在的子代。
由於Rc類型會自動取消引用,因此可以直接在其上調用RefCell方法。 它們是borrow_mut()
borrow()
和borrow_mut()
,它們返回對基礎節點的引用和可變引用。 還存在不會失敗的try_borrow()
和try_borrow_mut()
變體。
get_ref()
是Option類型的方法,該方法返回對基礎Rc<RefCell<Node>>
的引用。 在實際的Peogram中,我們可能需要事先檢查Option是否包含任何內容。
為什么原始代碼不起作用? 引用&T
非所有權,因此必須擁有其他節點。 雖然可以構建&Node
類型的樹,但無法修改樹外的Node,因為一旦借用后,除了借用對象外,其他任何對象都無法修改對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.