首页 文章

循环引用的寿命不够长

提问于
浏览
2

我有一个类似于循环图的结构,其中节点引用其他节点 . 我还是刚刚开始学习Rust,我用Rust borrowed pointers and lifetimeshttps://github.com/nrc/r4cppp/blob/master/graphs/src/rc_graph.rs作为参考

use std::cell::RefCell;
use std::rc::*;

fn main() {
    let node1 = Node::new(1);
    let node0 = Node::new(0);

    node0.borrow_mut().parent = Some(node1.clone());
    node1.borrow_mut().parent = Some(node0.clone());

    //works
    println!("Value of node0: {}", node0.borrow().value);

    //neither of the following work
    println!("Value of node0.parent: {}", node0.borrow().parent.as_ref().unwrap().borrow().value);
    println!("Value of node0: {}", node0.borrow().get_parent().borrow().value);
}

struct Node {
    value: i32,
    parent:  Option<Rc<RefCell<Node>>>
}

impl Node{

    fn new(val: i32) -> Rc<RefCell<Node>> {
        Rc::new(RefCell::new(Node {
            value: val,
            parent: None
        }))
    }


    fn get_parent(&self) -> Rc<RefCell<Node>> {
        self.parent.as_ref().unwrap().clone()
    }
}

我正在尝试输出节点父节点的值,但是我得到以下编译错误:

16 |     println!("Value of node0.parent: {}", node0.borrow().parent.as_ref().unwrap().borrow().value);
   |                                           ^^^^^^^^^^^^^^ does not live long enough

17 |     println!("Value of node0: {}", node0.borrow().get_parent().borrow().value);
   |                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^ does not live long enough

我究竟做错了什么?

1 回答

  • 2

    你需要从 println! 调用中分出借用:

    // Borrow them separately, so their scopes are larger.
    let n0_borrowed = node0.borrow();
    let n1_borrowed = node1.borrow();
    let n0_parent = n0_borrowed.parent.as_ref().unwrap();
    let n1_parent = n1_borrowed.parent.as_ref().unwrap();
    
    println!("Value of node0: {}", node0.borrow().value);
    println!("Value of node0.parent: {}", n0_parent.borrow().value);
    
    println!("Value of node1: {}",node1.borrow().value);
    println!("Value of node1.parent: {}", n1_parent.borrow().value);
    

    Here it is running in the Playground .

    从本质上讲,当您将所有呼叫链接在一起时,借用的引用的生存时间不够长 . 拆分它们可以扩大它们的范围,并且它们可以延长寿命 .

相关问题