首先,如果此问题以前已经被问过,请接受我的道歉。我能找到的唯一类似的问题是这个(但似乎不同):
我的代码是:
use std::cell::RefCell;
use std::rc::Rc;
type NodePointer = Option<Rc<RefCell<Node>>>;
#[derive(Debug)]
struct Node {
pub value : i32,
pub next : NodePointer
}
fn main() {
let mut vector = vec![None; 2];
let new_node = Rc::new(RefCell::new(Node {
value : 0,
next : None
}));
vector[1] = Some(Rc::clone(&new_node));
let new_node = Rc::new(RefCell::new(Node {
value : 0,
next : Some(Rc::clone(&new_node))
}));
vector[0] = Some(new_node);
println!("{:?}", vector);
// the following 3 lines would represent a body of the loop
let mut a = vector[0].as_ref(); // Option<&Rc<RefCell<Node>>>
let b = a.take().unwrap().borrow_mut(); // RefMut<Node>
a = b.next.as_ref(); //ERROR : borrowed value 'b' does not live long enough
println!("{:?}", vector);
}
下面的代码是我完整代码的一小部分。它有点奇怪,但变量'a'将用于循环遍历向量(完整代码中超过2个值)。
我试图做的是确保变量'a'被替换为向量[0]的'next'参数,而不修改向量。
编译器抱怨'b'的寿命不够长,但我不明白为什么会这样。
根据我的理解:
- 向量[0]是Option<Rc<...>> - 变量'a'是Option<&Rc<...>> - a.take() 不会 修改 vector[0] - a.take() 代替将'a'替换为None - borrow_mut() 应该给出对向量[0]的引用,但出于某种原因它没有?<- 我认为这就是问题所在 - 发生了什么事情,但我不知道发生了什么。
我知道我可以使用Option :: take()方法代替take_ref(),并且它在我的完整代码中与一些其他修改一起使用,但是我希望在两个println语句之间保持vector不被修改。
编辑: 为了提供信息,以下循环体将编译,但会修改向量...
let mut a = vector[0].take(); // Option<&Rc<RefCell<Node>>>
let temp = a.unwrap();
let mut b = temp.borrow_mut(); // RefMut<Node>
a = b.next.take(); //ERROR : borrowed value 'b' does not live long enough
borrow_mut()
应该给向量[0]
的一个引用,但出于某种原因它没有。实际上,它应该返回允许您在没有对RefCell
进行可变借用的情况下对RefCell
的内容进行可变借用的保护对象。 - Marko Topolnik