Use weak references to see if the variable has been released

use std::cell::RefCell;
use std::rc::{Rc, Weak};

use crate::List::{Cons, Nil};
use std::borrow::BorrowMut;

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

struct Test {
    valueA: Weak<List>,
    valueB: Weak<List>,
}

fn main() {

    let x=1;
    let x =2;
    let mut test = Test {
        valueA: Weak::new(),
        valueB: Weak::new(),
    };

    {
        let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil))));

        println!("a initial rc count = {}", Rc::strong_count(&a));
        println!("a next item = {:?}", a.tail());

        let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a))));

        println!("a rc count after b creation = {}", Rc::strong_count(&a));
        println!("b initial rc count = {}", Rc::strong_count(&b));
        println!("b next item = {:?}", b.tail());

        test.valueA = Rc::downgrade(&a);
        test.valueB = Rc::downgrade(&b);

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

        println!("b rc count after changing a = {}", Rc::strong_count(&b));
        println!("a rc count after changing a = {}", Rc::strong_count(&a));


        // Uncomment the next line to see that we have a cycle;
        // it will overflow the stack
        // println!("a next item = {:?}", a.tail());

        // drop(a);
        // drop(b);
        println!("in range A: {:?}", test.valueA.upgrade().is_none());
        println!("in range B: {:?}", test.valueB.upgrade().is_none());
    }

    println!("A: {:?}", test.valueA.upgrade().is_none());
    println!("B: {:?}", test.valueB.upgrade().is_none());
}

The principle is that as long as the variable is released, the value of the weak reference is "none".

It can also be judged based on whether Drop has been executed.

I am a game developer who suffers from a memory leak.