Ownership & Borrowing
versus Reference Counting

Rust's signature achievement is memory safety without a garbage collector. It accomplishes this through a disciplined ownership system — but that system deliberately has an escape hatch: reference counting.

Every value in a Rust program has a single owner at any given time. When that owner goes out of scope, the value is dropped — memory freed, deterministically, at a known point in execution. No GC pause, no dangling pointer, no double-free. The compiler enforces all of this statically.

But some data genuinely needs to be shared: a node in a graph owned by multiple edges, a configuration object threaded through many subsystems, a callback holding a reference into surrounding state. Enter reference countingRc<T> and Arc<T> — which shift ownership logic from compile time into a small runtime counter.

These are not competing features. They are complementary tools with distinct trade-offs. This article unpacks both — semantics, performance, ergonomics, and the decisive question: which should you reach for?


O&B

Ownership & Borrowing

The ownership model is Rust's core innovation. Every heap allocation has exactly one owner — the variable binding that "holds" it. Ownership can be moved to another binding, at which point the original is invalidated. It can never be silently copied (unless the type implements Copy).

Move Semantics

ownership_move.rs
fn main() {
    let s1 = String::from("hello");
    let s2 = s1;  // ownership MOVED — s1 is now invalid

    // println!("{}", s1);  ← compile error: value borrowed after move
    println!("{}", s2);  // fine — s2 is the sole owner
} // s2 dropped here, memory freed automatically

The borrow checker enforces the ownership rules. When s1 is assigned to s2, the compiler understands that s1 can no longer be used — it has given up ownership. This eliminates use-after-free at zero runtime cost.

Borrowing — Shared (&T) and Mutable (&mut T)

Moving ownership everywhere would be cumbersome. Rust lets you borrow a value: take a temporary, scoped reference without transferring ownership.

borrowing.rs
fn calculate_length(s: &String) -> usize {
    s.len()
}  // s goes out of scope but does NOT drop the String

fn append_world(s: &mut String) {
    s.push_str(", world");
}

fn main() {
    let mut greeting = String::from("hello");

    let len = calculate_length(&greeting); // shared borrow
    append_world(&mut greeting);          // mutable borrow

    println!("'{}' has {} characters", greeting, len);
}

The borrow checker enforces two invariants simultaneously:

This is aliasing XOR mutability — a fundamental rule that eliminates entire categories of bugs (iterator invalidation, data races) statically.

Lifetimes

References are augmented with lifetimes — annotations that prove a reference cannot outlive the data it points to. In most code the compiler infers them; in complex generic APIs you annotate explicitly.

lifetimes.rs
// 'a says: the returned reference lives at least as long as both inputs
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() >= y.len() { x } else { y }
}
Key Properties
Ownership & Borrowing is zero-cost: all safety guarantees are verified at compile time and produce no runtime overhead — no counter increments, no heap allocations beyond the value itself, no extra indirection.

Rc

Reference Counting: Rc<T> and Arc<T>

Ownership is a strict single-owner model. But some programs require shared ownership — multiple parts of a program that each need to keep a value alive. The classic example is a graph where multiple edges point to the same node.

Rc<T> (Reference Counted) wraps a value on the heap alongside a pair of counters: a strong count (active owners) and a weak count. Every clone of the Rc increments the strong count; every drop decrements it. When the strong count reaches zero, the inner value is dropped.

Basic Usage

rc_basic.rs
use std::rc::Rc;

fn main() {
    let a = Rc::new(String::from("shared data"));
    let b = Rc::clone(&a);  // increments strong count — cheap pointer clone
    let c = Rc::clone(&a);

    println!("strong count = {}", Rc::strong_count(&a)); // 3

    drop(b);
    println!("after drop b = {}", Rc::strong_count(&a)); // 2

} // a and c drop here; count → 0 → String is freed

Interior Mutability with RefCell

Rc<T> gives shared ownership but immutable access. To mutate the inner value you pair it with RefCell<T>, which moves borrow checking from compile time to runtime:

rc_refcell.rs
use std::rc::Rc;
use std::cell::RefCell;

fn main() {
    let shared = Rc::new(RefCell::new(vec![1, 2, 3]));

    let clone1 = Rc::clone(&shared);
    let clone2 = Rc::clone(&shared);

    clone1.borrow_mut().push(4);  // runtime borrow check
    clone2.borrow_mut().push(5);

    println!("{:?}", shared.borrow()); // [1, 2, 3, 4, 5]
}

Thread-Safe Sharing: Arc<T>

Rc<T> is not Send or Sync — its counter is not atomic and cannot cross thread boundaries. For concurrent use, swap in Arc<T> (Atomically Reference Counted), which uses atomic CPU operations for the counter. For interior mutability across threads, pair it with Mutex<T> or RwLock<T>.

arc_mutex.rs
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0u32));

    let handles: Vec<_> = (0..8).map(|_| {
        let c = Arc::clone(&counter);
        thread::spawn(move || {
            *c.lock().unwrap() += 1;
        })
    }).collect();

    for h in handles { h.join().unwrap(); }
    println!("count = {}", *counter.lock().unwrap()); // 8
}
Watch Out — Reference Cycles
Rc<T> and Arc<T> cannot automatically detect reference cycles. If two Rc values hold each other, their strong counts never reach zero and you leak memory. Use Weak<T> for back-references (e.g., parent pointers in a tree) to break cycles.

Side-by-Side Comparison

Dimension Ownership & Borrowing Rc<T> / Arc<T>
Ownership model Single owner, strictly enforced Shared ownership via counted handles
Verification Compile time — zero runtime cost Runtime — counter ops on every clone/drop
Performance Zero overhead — no extra indirection Small overhead: heap alloc, counter, pointer deref
Thread safety Enforced by Send/Sync compile-time Rc: single-thread only; Arc: thread-safe
Mutation &mut T — exclusive, statically checked Requires RefCell/Mutex — runtime panics possible
Cycles N/A — single owner can't cycle with itself Reference cycles leak memory — use Weak<T>
API complexity Steeper learning curve (lifetimes) Simpler surface; complexity moves to runtime
Typical use case Default for almost all data in Rust Graphs, trees with shared nodes, shared config, callbacks
Drop timing Deterministic — at end of owner's scope Deterministic — when last handle drops (may be non-obvious)
Cloning cost Deep copy (or move — free) Pointer copy + counter increment — O(1)

Performance in Practice

The overhead of Rc<T> is three-fold: one extra heap allocation for the control block, one pointer indirection on every access, and two integer increments/decrements on clone and drop. For most programs this is negligible. For hot-path code with millions of operations per second — game engines, compilers, signal processors — preferring owned values matters.

Arc<T> adds further cost: atomic operations use CPU memory-ordering guarantees (SeqCst or Release/Acquire), which inhibit certain compiler and hardware reorderings. On contended multi-core workloads, this can become measurable.

Rule of Thumb
Reach for Rc/Arc when the alternative is fighting the borrow checker with complex lifetime annotations or unsafe code. The small runtime cost buys you ergonomic, safe shared ownership — a reasonable trade in most application code.

?

Decision Guide

Prefer Ownership + Borrowing when…

Prefer Rc<T> / Arc<T> when…

graph_node.rs
// Classic use case: graph with shared nodes
use std::rc::{Rc, Weak};
use std::cell::RefCell;

struct Node {
    value: i32,
    children: Vec<Rc<RefCell<Node>>>>,
    parent: Option<Weak<RefCell<Node>>>>, // Weak breaks parent→child cycle
}

impl Node {
    fn new(value: i32) -> Rc<RefCell<Node>> {
        Rc::new(RefCell::new(Node {
            value,
            children: vec![],
            parent: None,
        }))
    }
}