gpt4 book ai didi

rust - 循环引用的生命周期不够长

转载 作者:行者123 更新时间:2023-11-29 08:07:54 24 4
gpt4 key购买 nike

我有一个类似循环图的结构,其中节点引用其他节点。为了简洁起见,我删除了一些内容。我刚开始学习 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

我做错了什么?

最佳答案

您需要从 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 .

从本质上讲,当您将所有调用链接在一起时,借用的引用不会存在足够长的时间。将它们分离出来会增加它们的范围并延长它们的生命周期。

关于rust - 循环引用的生命周期不够长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40274049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com