Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of Rc when the inner value is mutated

Tags:

rust

In the following code snippet, why does the count-1 prints 3 and count-2 prints 1. When the inner value of a Rc is mutated, why is it dropping b and c as reference holders? What is the behavior of Rc in such a case?

#[derive(Debug)]
enum List {
    Cons(u32, Rc<List>),
    Nil,
}

use crate::List::{Cons, Nil};

fn main() {
    let mut a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Cons(15, Rc::new(Nil)))))));
    let b = Cons(25, Rc::clone(&a));
    let c = Cons(30, Rc::clone(&a));

    println!("count-1 {}", Rc::strong_count(&a));

    let d = &mut a;
    *d = Rc::new(Cons(1, Rc::new(Nil)));

    println!("count-2 {}", Rc::strong_count(&a));
}
like image 356
devj Avatar asked Oct 27 '25 13:10

devj


1 Answers

When the inner value of a Rc is mutated, why is it dropping b and c as reference holders?

There's no mutating of inner values here, what you're doing is essentially the same as

a = Rc::new(Cons(1, Rc::new(Nil)));

So you're setting a to a brand new Rc, with a refcount of 1. b and c remain as-is, and the node a used to be has a remaining refcount of 2. Which you can see by accessing it via b or c e.g.

let Cons(_, a2) = &b else {
    return;
};
println!("{}", Rc::strong_count(a2));
like image 80
Masklinn Avatar answered Oct 30 '25 11:10

Masklinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!