Box, Rc & RefCell

Heap allocation, shared ownership with reference counting, and interior mutability.

Ownership has one owner per value, but some data structures need more: recursive types, values shared by several owners, or shared values that must still change. Smart pointers handle these cases while keeping memory safety.

An expression tree and a shared bus

Box<Expr> puts each sub-expression on the heap, giving the recursive enum a known size.

Rc::clone does not copy the bus; it increments a reference count (3 owners: bus, ecu, bms).

RefCell::borrow_mut lets nodes append to the shared log even though they only hold shared Rc pointers.

Dropping ecu decrements the count to 2; the bus is freed when the count reaches 0.

RefCell checks the borrowing rule at run time: a mutable borrow while a shared one is active is refused.

Which pointer when

let a = bus.borrow_mut(); let b = bus.borrow_mut(); // panics: already mutably borrowed

Keep RefCell borrows short: { bus.borrow_mut().log.push(...); }

RefCell enforces the borrow rules at run time, so overlapping mutable borrows panic. Limit each borrow to a small scope.

What is the difference between Rc and Arc?

Both provide shared ownership with reference counting. Rc's count is not thread-safe (faster); Arc uses atomic operations so it can be shared between threads.