Reference Cycle and strong count

⚓ Rust    📅 2025-07-27    👤 surdeus    👁️ 12      

surdeus

Warning

This post was published 129 days ago. The information described in this article may have changed.

I am trying to understand an example of cyclical references.

First take this non-cyclical snippet and comments within:

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


fn main() {
    // comments are the Rc strong counts.   
    let a = Rc::new(5); // a = 1
    let b = Rc::new([Rc::clone(&a)]); // a = 2, b = 1
} // a = 1, b = 0      --- b is dropped
// a = 0               --- a dropped

That's how I expect things to happen at a conceptual level.

Here, the Rust Book gives an example of cyclical references.

The main bit is (with stripped out comments):

What I expected is (in comments again):

fn main() {
    let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); // a = 1

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

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

I am aware this is wrong, but I don't know how should I think about this.

The explanation in the book did not click for me.

This is just for understanding, so don't worry about fixes.

2 posts - 2 participants

Read full topic

🏷️ Rust_feed