Initial commit.

This commit is contained in:
rust-lang.xfoss.com
2023-03-27 14:33:48 +08:00
commit cf2b9a266c
266 changed files with 23587 additions and 0 deletions

View 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]

View 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());
}