# `Rc` Reference Counted Smart Pointer Allocate data in heap for multiple users to Read, without needing to know who will be the last reader - Only for SingleThread tho. ## Sharing Data with `Rc` Ex: List `a` contains 2 values, List `b` and `c` have other values first and then continue with values from `a` Both need access to `a` ```rust enum List { Cons(i32, Box), Nil, } use crate::List::{Cons, Nil}; fn main() { let a = Cons(5, Box::new(Cons(10, Box::new(Nil)))); let b = Cons(3, Box::new(a)); let c = Cons(4, Box::new(a)); } ``` Here, ownership of `a` is moved to `b`, thus `c` is asking for ownership from a non-owner. That is because `Cons` owns the data it holds. To change that into references, it would be a mess: ```rust // Add lifetime so that List and References have the same lifetime enum List<'a> { Cons(i32, Box<&'a List<'a>>), Nil, } use List::*; // Now Box can't own data, so it owns a reference of some data // Have to declare a variable Nil to own the actual data // Then declare the first node to own `10` and ref to `Nil` // Then a owns `5` and references `list_a`,... fn main() { let nil_v = Nil; let list_a = Cons(10, Box::new(&nil_v)); let a = Cons(5, Box::new(&list_a)); let b = Cons(3, Box::new(&a)); let c = Cons(4, Box::new(&a)); } ``` But with `Rc` ```rust enum List { Cons(i32, Rc), Nil, } use List::*; use std::rc::Rc; fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); let b = Cons(3, Rc::clone(&a)); let c = Cons(4, Rc::clone(&a)); } ``` List now holds a `Reference Counted Smart Pointer` to a List. Then each other list will have a clone of the reference - `clone` method does not clone all data, it only increments the reference count by 1. When that clone is dropped, it drops the count by 1, if count gets to 0, the values is dropped. ```rust fn main() { let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); println!("count after creating a = {}", Rc::strong_count(&a)); let b = Cons(3, Rc::clone(&a)); println!("count after creating b = {}", Rc::strong_count(&a)); { let c = Cons(4, Rc::clone(&a)); println!("count after creating c = {}", Rc::strong_count(&a)); } println!("count after c goes out of scope = {}", Rc::strong_count(&a)); } // Output count after creating a = 1 count after creating b = 2 count after creating c = 3 count after c goes out of scope = 2 ``` To know exactly number of references use `Rc::strong_count(&self)` `Rc::weak_count(&self)` explained later...