Rust編程進階:039、引用循環

一個循環鏈表的例子:

#[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,
        }
    }
}

use crate::List::{Cons, Nil};
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));
    println!("1, a rc count = {}", Rc::strong_count(&a));
    println!("1, a tail = {:?}", a.tail());

    {
        let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));
        println!("2, a rc count = {}", Rc::strong_count(&a));
        println!("2, b rc count = {}", Rc::strong_count(&b));
        println!("2, b tail = {:?}", b.tail());

        if let Some(link) = a.tail() {
            *link.borrow_mut() = Rc::clone(&b);
        }

        println!("3, a rc count = {}", Rc::strong_count(&a));
        println!("3, b rc count = {}", Rc::strong_count(&b));
        // println!("3, a tail = {:?}", a.tail()); // 死循環,會造成棧的溢出
    }
}

本節全部源代碼:
https://github.com/anonymousGiga/learn_rust/blob/master/learn_loop_ref/src/main.rs

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章