【发布时间】:2015-05-08 23:00:22
【问题描述】:
我尝试这段代码时出错,它实现了一个简单的链表。
use std::rc::Rc;
use std::cell::RefCell;
struct Node {
a : Option<Rc<RefCell<Node>>>,
value: i32
}
impl Node {
fn new(value: i32) -> Rc<RefCell<Node>> {
let node = Node {
a: None,
value: value
};
Rc::new(RefCell::new(node))
}
}
fn main() {
let first = Node::new(0);
let mut t = first.clone();
for i in 1 .. 10_000
{
if t.borrow().a.is_none() {
t.borrow_mut().a = Some(Node::new(i));
}
if t.borrow().a.is_some() {
t = t.borrow().a.as_ref().unwrap().clone();
}
}
println!("Done!");
}
为什么会这样?这是否意味着 Rust 不如定位安全?
更新: 如果我添加这个方法,程序不会崩溃。
impl Drop for Node {
fn drop(&mut self) {
let mut children = mem::replace(&mut self.a, None);
loop {
children = match children {
Some(mut n) => mem::replace(&mut n.borrow_mut().a, None),
None => break,
}
}
}
}
但我不确定这是否是正确的解决方案。
【问题讨论】:
-
确切的错误是什么?在编译时还是运行时?
-
编译正常。运行程序时出现此错误
-
这是否意味着 Rust 不如定位安全? - 请在 Rust 的上下文中review what safety means。在这种情况下,“安全”不意味着程序不能中止。
标签: rust