mirror of
https://github.com/gnu4cn/rust-lang-zh_CN.git
synced 2026-08-22 14:13:28 +08:00
Initial commit.
This commit is contained in:
8
ref_cycle_demo/Cargo.toml
Normal file
8
ref_cycle_demo/Cargo.toml
Normal file
@@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "ref_cycle_demo"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
42
ref_cycle_demo/src/main.rs
Normal file
42
ref_cycle_demo/src/main.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use crate::List::{Cons, Nil};
|
||||
|
||||
#[derive(Debug)]
|
||||
enum List {
|
||||
Cons(i32, RefCell<Rc<List>>),
|
||||
Nil,
|
||||
}
|
||||
|
||||
impl List {
|
||||
fn tail(&self) -> Option<&RefCell<Rc<List>>> {
|
||||
match self {
|
||||
Cons(_, item) => Some(item),
|
||||
Nil => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
|
||||
|
||||
println! ("a 的初始 rc 计数 = {}", Rc::strong_count(&a));
|
||||
println! ("a 的下一条目 = {:?}", a.tail());
|
||||
|
||||
let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));
|
||||
|
||||
println! ("b 的创建后 a 的 rc 计数 = {}", Rc::strong_count(&a));
|
||||
println! ("b 的初始 rc 计数 = {}", Rc::strong_count(&b));
|
||||
println! ("b 的下一条目 = {:?}", b.tail());
|
||||
|
||||
if let Some(link) = a.tail() {
|
||||
*link.borrow_mut() = Rc::clone(&b);
|
||||
}
|
||||
|
||||
println! ("在修改 a 之后 b 的 rc 计数 = {}", Rc::strong_count(&b));
|
||||
println! ("在修改 a 之后 a 的 rc 计数 = {}", Rc::strong_count(&a));
|
||||
|
||||
// 取消下面这行注释,就可以看到这里有着循环引用;
|
||||
// 他将溢出堆栈(it will overflow the stack)
|
||||
// println! ("a 的下一条目 = {:?}", a.tail());
|
||||
}
|
||||
Reference in New Issue
Block a user