Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    Module 11 · Lifetimes & smart pointers

    11.3Shared ownership & interior mutability

    How to give one value several owners with Rc and Arc, change shared data with Cell and RefCell, break reference cycles with Weak, and when to avoid all of them.

    About 35 minutesAdvanced

    On this page
    1. Concept map
    2. Rc<T>: several owners, one value
    3. Arc<T>: sharing across threads
    4. Changing shared data: Cell<T> and RefCell<T>
    5. Cell<T>: for small Copy values
    6. Weak<T>: pointing back without owning
    7. Which one should I use?
    8. Under the hood
    9. Common pitfalls
    10. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Several parts of a program holding the same objectThe default for every objectThe default for every class instanceOpt-in: Rc<T> on one thread, Arc<T> across threads
    When a shared object is freedWhen the garbage collector finds it unreachableWhen the garbage collector finds it unreachableWhen the last Rc or Arc pointing at it is dropped
    Changing an object that others also holdAllowed through any referenceAllowed through any reference (unless it's immutable)Only through Cell<T>, RefCell<T>, an atomic, or a lock such as Mutex<T>
    Two writers at onceAllowedAllowedRefCell refuses at run time: try_borrow_mut returns Err, borrow_mut panics
    Parent and child objects that point at each otherFine; the garbage collector handles cyclesFine; the garbage collector handles cyclesChild to parent with Weak<T>, or the cycle leaks

    In TypeScriptC#, any number of variables, fields and lists can refer to the same object, and any of them can change it. The garbage collector works out when the last one lets go. That’s convenient, and it’s also how two parts of a program end up changing the same object without knowing about each other. Rust’s default is the opposite: one owner, plus borrows the compiler checks. Most code never needs more. When a value really does need several owners, such as a config shared by several services, a node in a tree, or a cache, you opt in with a reference-counted pointer: Rc<T> on one thread, Arc<T> across threads. And when shared data must also change, you opt in again, with Cell<T> or RefCell<T>. Every opt-in shows up in the type.

    Rc<T>: several owners, one value

    Here’s a config shared by a server and a logger. In TypeScriptC#, both hold a reference to the same object, and that’s all there is to it. In Rust, a plain Config field would give each of them its own copy, or move the config into one of them. To share one value, put it in an Rc (“reference counted”) and give each owner a clone of the Rc.

    TypeScript
    config.ts
    type Config = { name: string; port: number };
    type Server = { config: Config };
    type Logger = { config: Config };
    
    const config: Config = { name: "api", port: 8080 };
    const server: Server = { config };
    const logger: Logger = { config };
    console.log(`server on port ${server.config.port}`);
    console.log(`logger for ${logger.config.name}`);
    C#
    Config.cs
    var config = new Config("api", 8080);
    var server = new Server(config);
    var logger = new Logger(config);
    Console.WriteLine($"server on port {server.Config.Port}");
    Console.WriteLine($"logger for {logger.Config.Name}");
    
    record Config(string Name, int Port);
    record Server(Config Config);
    record Logger(Config Config);
    Rust
    use std::rc::Rc;
    
    struct Config {
        name: String,
        port: u16,
    }
    
    struct Server {
        config: Rc<Config>,
    }
    
    struct Logger {
        config: Rc<Config>,
    }
    
    fn main() {
        let config = Rc::new(Config {
            name: String::from("api"),
            port: 8080,
        });
        let server = Server {
            config: Rc::clone(&config),
        };
        let logger = Logger {
            config: Rc::clone(&config),
        };
        println!("server on port {}", server.config.port);
        println!("logger for {}", logger.config.name);
    }

    Output

    server on port 8080
    logger for api

    Rc::new moves the Config into a heap allocation next to a counter. Rc::clone(&config) doesn’t copy the config: it copies the pointer and adds one to the counter. Every Rc is an owner. When one is dropped, the counter goes down, and when the last one is dropped, the Config is dropped and its memory freed. server.config.port works through Deref, as in Drop & smart pointers.

    You can watch the count with Rc::strong_count:

    use std::rc::Rc;
    
    struct Config {
        name: String,
        port: u16,
    }
    
    fn main() {
        let config = Rc::new(Config {
            name: String::from("api"),
            port: 8080,
        });
        println!("after new: {}", Rc::strong_count(&config));
        let server = Rc::clone(&config);
        println!("after clone: {}", Rc::strong_count(&config));
        {
            let logger = Rc::clone(&config);
            println!("inside the block: {}", Rc::strong_count(&logger));
        } // `logger` is dropped: the count goes down
        println!("after the block: {}", Rc::strong_count(&config));
        drop(server);
        println!("after drop(server): {}", Rc::strong_count(&config));
        println!("{} still on port {}", config.name, config.port);
    }

    Output

    after new: 1
    after clone: 2
    inside the block: 3
    after the block: 2
    after drop(server): 1
    api still on port 8080

    Here’s memory just after let server = Rc::clone(&config); in count.rs, when the count is 2:

    Two Rc pointers to one ConfigOn the stack, config and server are each an Rc<Config>: a single pointer. Both pointers lead to the same heap allocation. That allocation starts with two counters, a strong count of 2 (the two Rc owners) and a weak count of 0, followed by the Config itself with name api and port 8080. The name's own text buffer is a separate heap allocation, not drawn. Dropping either Rc lowers the strong count; when it reaches 0, the Config is dropped.StackHeapconfig: Rc<Config>ptrserver: Rc<Config>ptrRc allocationstrong: 2weak: 0name: "api"port: 8080
    Two Rc pointers to one Config. On the stack, config and server are each an Rc<Config>: a single pointer. Both pointers lead to the same heap allocation. That allocation starts with two counters, a strong count of 2 (the two Rc owners) and a weak count of 0, followed by the Config itself with name api and port 8080. The name's own text buffer is a separate heap allocation, not drawn. Dropping either Rc lowers the strong count; when it reaches 0, the Config is dropped.

    Mental model shiftShared means read-only

    Through Deref, an Rc<T> only gives you a &T. (Rc::get_mut hands out a &mut T only while there’s a single owner, which rules out sharing.) That’s the borrowing rule from References applied to owners: when several parts of a program can reach a value, none of them may change it unchecked. Assigning through an Rc doesn’t compile:

    use std::rc::Rc;
    
    struct Config {
        port: u16,
    }
    
    fn main() {
        let config = Rc::new(Config { port: 8080 });
        config.port = 9090;
    }

    Rust doesn't compile this: error E0594

    error[E0594]: cannot assign to data in an `Rc`
     --> main.rs:9:5
      |
    9 |     config.port = 9090;
      |     ^^^^^^^^^^^^^^^^^^ cannot assign
      |
      = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Rc<Config>`

    To change shared data, you need interior mutability, below.

    Arc<T>: sharing across threads

    Rc updates its counter with ordinary additions, which is fast but not safe if two threads clone or drop at the same moment. The compiler stops an Rc from reaching another thread at all:

    use std::rc::Rc;
    use std::thread;
    
    struct Config {
        port: u16,
    }
    
    fn main() {
        let config = Rc::new(Config { port: 8080 });
        let shared = Rc::clone(&config);
        let handle = thread::spawn(move || println!("port {}", shared.port));
        handle.join().expect("the thread panicked");
    }

    Rust doesn't compile this: error E0277

    error[E0277]: `Rc<Config>` cannot be sent between threads safely
      --> main.rs:11:32
       |
    11 |     let handle = thread::spawn(move || println!("port {}", shared.port));
       |                  ------------- -------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
       |                  |             |
       |                  |             `Rc<Config>` cannot be sent between threads safely
       |                  |             within this `{closure@main.rs:11:32: 11:39}`
       |                  required by a bound introduced by this call
       |
       = help: within `{closure@main.rs:11:32: 11:39}`, the trait `Send` is not implemented for `Rc<Config>`
    note: required because it's used within this closure
      --> main.rs:11:32
       |
    11 |     let handle = thread::spawn(move || println!("port {}", shared.port));
       |                                ^^^^^^^
    note: required by a bound in `spawn`

    Arc<T> (“atomically reference counted”) works like Rc<T>, but its counter uses atomic CPU instructions, so it’s safe to clone and drop from any thread. The API is the same:

    use std::sync::Arc;
    use std::thread;
    
    struct Config {
        port: u16,
    }
    
    fn main() {
        let config = Arc::new(Config { port: 8080 });
        let mut handles = Vec::new();
        for id in 1..=2 {
            let config = Arc::clone(&config);
            handles.push(thread::spawn(move || {
                format!("worker {id} on port {}", config.port)
            }));
        }
        for handle in handles {
            println!("{}", handle.join().expect("the worker panicked"));
        }
    }

    Output

    worker 1 on port 8080
    worker 2 on port 8080

    JavaScript workers don’t share objects: messages between them are copied or transferred, so TypeScript code never has this problem, and never has this option either.In C#, any thread can hold any object, and nothing checks whether the object is safe to share. Rust’s check comes from two marker traits, Send and Sync. Send & Sync explains the rule behind the E0277 above. Atomic updates cost a little more, so use Rc unless the value crosses threads; the compiler tells you when it does.

    Changing shared data: Cell<T> and RefCell<T>

    The borrowing rule, many readers or one writer, is normally checked at compile time. Interior mutability moves the check: a RefCell<T> lets you change its contents through a shared &RefCell<T>, and checks the rule at run time instead. Combined with Rc, you get the TypeScriptC# default, a shared object anyone can change, but you have to ask for it.

    Here two components append to one shared log:

    TypeScript
    log.ts
    class Component {
      readonly name: string;
      readonly log: string[];
    
      constructor(name: string, log: string[]) {
        this.name = name;
        this.log = log;
      }
    
      record(event: string): void {
        this.log.push(`${this.name}: ${event}`);
      }
    }
    
    const log: string[] = [];
    const server = new Component("server", log);
    const worker = new Component("worker", log);
    server.record("started");
    worker.record("finished job 1");
    for (const line of log) {
      console.log(line);
    }
    C#
    Log.cs
    var log = new List<string>();
    var server = new Component("server", log);
    var worker = new Component("worker", log);
    server.Record("started");
    worker.Record("finished job 1");
    foreach (var line in log)
    {
        Console.WriteLine(line);
    }
    
    class Component(string name, List<string> log)
    {
        public void Record(string @event) => log.Add($"{name}: {@event}");
    }
    Rust
    use std::cell::RefCell;
    use std::rc::Rc;
    
    type Log = Rc<RefCell<Vec<String>>>;
    
    struct Component {
        name: String,
        log: Log,
    }
    
    impl Component {
        fn new(name: &str, log: &Log) -> Self {
            Self {
                name: name.to_string(),
                log: Rc::clone(log),
            }
        }
    
        fn record(&self, event: &str) {
            let line = format!("{}: {event}", self.name);
            self.log.borrow_mut().push(line);
        }
    }
    
    fn main() {
        let log: Log = Rc::new(RefCell::new(Vec::new()));
        let server = Component::new("server", &log);
        let worker = Component::new("worker", &log);
        server.record("started");
        worker.record("finished job 1");
        for line in log.borrow().iter() {
            println!("{line}");
        }
    }

    Output

    server: started
    worker: finished job 1

    record takes &self, and still changes the log: self.log.borrow_mut() asks the RefCell for a mutable borrow of the Vec and returns a guard, a RefMut<Vec<String>>. The guard derefs to &mut Vec<String>, and dropping it (at the end of the statement here) ends the borrow. borrow() works the same way for reading and returns a Ref. Both guards are smart pointers like those in the previous lesson.

    What RefCell checks at run time is exactly what the compiler checks for & and &mut. While any Ref is alive, you can’t get a RefMut. try_borrow_mut reports that as an Err:

    use std::cell::RefCell;
    
    let log = RefCell::new(vec![String::from("started")]);
    let reader = log.borrow();
    match log.try_borrow_mut() {
        Ok(mut lines) => lines.push(String::from("stopped")),
        Err(error) => println!("can't write: {error}"),
    }
    println!("{} line, first: {}", reader.len(), reader[0]);
    drop(reader); // the read borrow ends here
    log.borrow_mut().push(String::from("stopped"));
    println!("{} lines", log.borrow().len());

    Output

    can't write: RefCell already borrowed
    1 line, first: started
    2 lines

    borrow_mut() does the same check, but instead of returning an Err, it panics with that same message. The code below compiles and then crashes when it runs, which is why it’s not run here:

    use std::cell::RefCell;
    
    let log = RefCell::new(vec![String::from("started")]);
    let reader = log.borrow();
    log.borrow_mut().push(String::from("stopped")); // panics: `reader` is still alive
    println!("{}", reader.len());

    The same mistake with plain & and &mut is a compile error (E0502). RefCell trades that compile-time error for a run-time panic, which is the price of sharing.

    Cell<T>: for small Copy values

    For a number or a bool, there’s a lighter tool. Cell<T> never lends out its contents at all: get() copies the value out, and set() copies a new one in. With no references to track, there’s nothing to check, at compile time or at run time. Here’s a cache that counts its hits through &self:

    use std::cell::Cell;
    
    struct Cache {
        value: String,
        hits: Cell<u32>,
    }
    
    impl Cache {
        fn get(&self) -> &str {
            self.hits.set(self.hits.get() + 1);
            &self.value
        }
    }
    
    fn main() {
        let cache = Cache {
            value: String::from("cached page"),
            hits: Cell::new(0),
        };
        println!("{}", cache.get());
        println!("{}", cache.get());
        println!("hits: {}", cache.hits.get());
    }

    Output

    cached page
    cached page
    hits: 2

    get only needs &self, so callers can share the cache freely, and counting doesn’t change that. Neither Cell nor RefCell can be shared between threads; across threads, the same jobs are done by atomics (AtomicU32) and locks (Mutex<T>, RwLock<T>), covered in Threads, channels & shared state.

    Weak<T>: pointing back without owning

    Reference counting has one blind spot. If two values hold an Rc to each other, each keeps the other’s count above zero, and neither is ever dropped. Here’s a cycle of two nodes. Neither drop message is ever printed:

    use std::cell::RefCell;
    use std::rc::Rc;
    
    struct Node {
        name: &'static str,
        next: RefCell<Option<Rc<Node>>>,
    }
    
    impl Drop for Node {
        fn drop(&mut self) {
            println!("drop {}", self.name);
        }
    }
    
    fn main() {
        let a = Rc::new(Node {
            name: "a",
            next: RefCell::new(None),
        });
        let b = Rc::new(Node {
            name: "b",
            next: RefCell::new(Some(Rc::clone(&a))),
        });
        // a -> b -> a: a cycle
        *a.next.borrow_mut() = Some(Rc::clone(&b));
        println!("a has {} owners", Rc::strong_count(&a));
        println!("b has {} owners", Rc::strong_count(&b));
        println!("end of main");
    } // the counts drop to 1, not 0: both nodes leak

    Output

    a has 2 owners
    b has 2 owners
    end of main

    That’s a memory leak, and it’s allowed in safe Rust: leaking is a bug, but not a memory-safety problem. TypeScriptC# doesn’t have this problem, because a tracing garbage collector frees unreachable cycles.

    The fix is to decide which direction owns. In a tree, parents own their children, and a child’s link back to its parent is a Weak<T>: a pointer that doesn’t count as an owner. Rc::downgrade(&rc) makes one, and weak.upgrade() returns an Option<Rc<T>>: Some if the value is still alive, None if it’s been dropped.

    TypeScript
    tree.ts
    type TreeNode = { name: string; parent: TreeNode | undefined; children: TreeNode[] };
    
    const root: TreeNode = { name: "root", parent: undefined, children: [] };
    const leaf: TreeNode = { name: "leaf", parent: undefined, children: [] };
    leaf.parent = root;
    root.children.push(leaf);
    if (leaf.parent) {
      console.log(`${leaf.name}'s parent is ${leaf.parent.name}`);
    }
    console.log(`${root.name} has ${root.children.length} child`);
    C#
    Tree.cs
    var root = new TreeNode("root");
    var leaf = new TreeNode("leaf");
    leaf.Parent = root;
    root.Children.Add(leaf);
    if (leaf.Parent is { } parent)
    {
        Console.WriteLine($"{leaf.Name}'s parent is {parent.Name}");
    }
    Console.WriteLine($"{root.Name} has {root.Children.Count} child");
    
    class TreeNode(string name)
    {
        public string Name { get; } = name;
        public TreeNode? Parent { get; set; }
        public List<TreeNode> Children { get; } = [];
    }
    Rust
    use std::cell::RefCell;
    use std::rc::{Rc, Weak};
    
    struct TreeNode {
        name: String,
        parent: RefCell<Weak<TreeNode>>,
        children: RefCell<Vec<Rc<TreeNode>>>,
    }
    
    impl TreeNode {
        fn new(name: &str) -> Rc<TreeNode> {
            Rc::new(TreeNode {
                name: name.to_string(),
                parent: RefCell::new(Weak::new()),
                children: RefCell::new(Vec::new()),
            })
        }
    }
    
    fn main() {
        let root = TreeNode::new("root");
        let leaf = TreeNode::new("leaf");
        // the child points back weakly; the parent owns the child
        *leaf.parent.borrow_mut() = Rc::downgrade(&root);
        root.children.borrow_mut().push(Rc::clone(&leaf));
        if let Some(parent) = leaf.parent.borrow().upgrade() {
            println!("{}'s parent is {}", leaf.name, parent.name);
        }
        println!("{} has {} child", root.name, root.children.borrow().len());
    }

    Output

    leaf's parent is root
    root has 1 child

    The fields are wrapped in RefCell because the nodes live inside Rcs, which only hand out &TreeNode, and the links are filled in after the nodes are created. Here’s what the counts look like, and what happens when the root goes away:

    let root = TreeNode::new("root");
    let leaf = TreeNode::new("leaf");
    *leaf.parent.borrow_mut() = Rc::downgrade(&root);
    root.children.borrow_mut().push(Rc::clone(&leaf));
    println!("root: strong {}", Rc::strong_count(&root));
    println!("root: weak {}", Rc::weak_count(&root));
    println!("leaf: strong {}", Rc::strong_count(&leaf));
    drop(root);
    let parent = leaf.parent.borrow().upgrade();
    println!("parent after drop: {}", parent.is_some());
    println!("leaf: strong {}", Rc::strong_count(&leaf));

    Output

    root: strong 1
    root: weak 1
    leaf: strong 2
    parent after drop: false
    leaf: strong 1
    A parent and a child, before drop(root)On the stack, root and leaf are each an Rc<TreeNode> pointing at their own heap allocation. root's allocation has a strong count of 1 (the root variable) and a weak count of 1 (the leaf's parent link); its children list holds an Rc to the leaf. leaf's allocation has a strong count of 2 (the leaf variable and root's children list) and a weak count of 0; its parent field is a Weak pointer to root, which doesn't count as an owner. When root is dropped, its strong count reaches 0, so the root node is dropped and the leaf's count goes back to 1.StackHeaproot: Rc<TreeNode>ptrleaf: Rc<TreeNode>ptrroot nodestrong: 1weak: 1children: [Rc to leaf]parent: noneleaf nodestrong: 2weak: 0children: []parent: Weak to root
    A parent and a child, before drop(root). On the stack, root and leaf are each an Rc<TreeNode> pointing at their own heap allocation. root's allocation has a strong count of 1 (the root variable) and a weak count of 1 (the leaf's parent link); its children list holds an Rc to the leaf. leaf's allocation has a strong count of 2 (the leaf variable and root's children list) and a weak count of 0; its parent field is a Weak pointer to root, which doesn't count as an owner. When root is dropped, its strong count reaches 0, so the root node is dropped and the leaf's count goes back to 1.

    Dropping root takes its strong count to 0, even though the leaf still points at it, so the root node is dropped, which drops its children list, which lowers the leaf’s count. Nothing leaks.

    Which one should I use?

    WhatWhenWhyHow
    Plain ownership (T, &T, &mut T)One part of the program owns the value and lends it out. The default.Checked at compile time, no counters, no run-time failures.let config = Config { ... };, pass &config.
    Box<T>One owner, but the value must be on the heap: a recursive type or a trait object.A single owner with no counting.Box::new(value)
    Rc<T>Several owners on one thread, and you can’t say which one lives longest.The value lives until the last owner is dropped. Read-only.Rc::new(value), then Rc::clone(&rc) for each owner.
    Arc<T>Several owners across threads.Like Rc, with an atomic counter that’s safe between threads.Arc::new(value), Arc::clone(&arc) per thread.
    Cell<T>A small Copy value (a counter, a flag) that must change behind &self.No references handed out, so no checks and no overhead. One thread only.hits: Cell<u32>, self.hits.set(self.hits.get() + 1)
    RefCell<T>A larger value that must change behind &self or inside an Rc.The borrowing rules, checked at run time. One thread only.log.borrow(), log.borrow_mut(), or try_borrow_mut() to avoid a panic.
    Rc<RefCell<T>>Several owners on one thread, and they all change the value.Shared and changeable, like a TypeScriptC# object.Rc::new(RefCell::new(value))
    Weak<T>A back-pointer (child to parent, observer to subject) that mustn’t keep its target alive.Breaks reference cycles, so nothing leaks.Rc::downgrade(&rc), then weak.upgrade() returns an Option.
    Arc<Mutex<T>>Several threads change the same value.A lock instead of RefCell’s run-time check.Module 12: Threads, channels & shared state.

    Rule of thumb: start with one owner and borrows. Reach for Rc (or Arc across threads) only when there’s genuinely no single owner, and add RefCell (or Mutex) only when the shared value must change. Use Cell for counters and flags, and Weak for any pointer that goes back up a structure.

    Which owner type?
    1. Can one part of the program own the value and lend it to the rest with & or &mut?

      Yes

      Plain ownership: T, or Box<T> for a recursive type or trait objectMost values. No counters, and every mistake is a compile error.

      No
    2. Must the value change through &self (a counter, a flag, a cache) while ownership stays simple?

      Yes

      Cell<T> for a Copy value, RefCell<T> for anything elseOne thread only. Across threads, use an atomic or a Mutex<T>.

      No
    3. Do several threads need to own it?

      Yes

      Arc<T>, with a Mutex<T> or RwLock<T> inside if they change itRc won't compile there (E0277).

      No
    4. Do several owners on one thread need to change it?

      Yes

      Rc<RefCell<T>>Check whether one owner plus &mut would do first. Use Weak<T> for back-pointers.

      No
    5. Otherwise: Rc<T>: several read-only owners on one thread. Make back-pointers Weak<T>.

    Under the hood

    An Rc<T> is a single pointer. The allocation it points at holds two counters followed by the value: the strong count (owners) and the weak count (Weak pointers). Rc::clone adds one to the strong count, dropping an Rc subtracts one, and when the strong count reaches 0 the value is dropped. The allocation itself is freed once no Weak pointers are left either, so a Weak can always safely read the counters to find out that the value is gone. Arc<T> has the same layout, with atomic counters.

    Cell<T> adds nothing: it’s the value itself, and the type system does the rest. RefCell<T> adds a borrow flag, a counter of how many Refs are alive, with a special value for one RefMut. borrow() and borrow_mut() check and update it; dropping the guard undoes the update.

    use std::cell::{Cell, RefCell};
    use std::rc::{Rc, Weak};
    use std::sync::Arc;
    
    println!("Cell<i32>: {} bytes", size_of::<Cell<i32>>());
    println!("RefCell<i32>: {} bytes", size_of::<RefCell<i32>>());
    println!("Rc<i32>: {} bytes", size_of::<Rc<i32>>());
    println!("Arc<i32>: {} bytes", size_of::<Arc<i32>>());
    println!("Weak<i32>: {} bytes", size_of::<Weak<i32>>());

    Output

    Cell<i32>: 4 bytes
    RefCell<i32>: 16 bytes
    Rc<i32>: 8 bytes
    Arc<i32>: 8 bytes
    Weak<i32>: 8 bytes
    Cell<i32> and RefCell<i32> in memory
    Cell<i32> and RefCell<i32> in memory: each row is one value; each cell's width is its size in bytes.
    Value0123456789101112131415Size
    Cell<i32>value4 bytes4 bytes
    RefCell<i32>borrow flag8 bytesvalue4 bytespadding4 bytes16 bytes

    Each row is drawn to scale in bytes, today, on a 64-bit target. A Cell<i32> is 4 bytes: just the i32. A RefCell<i32> is 16 bytes: an 8-byte borrow flag that counts the live borrows, the 4-byte i32, and 4 bytes of padding to keep the size a multiple of 8. Rust doesn't fix the order of these fields; this is one possible order.

    None of this is free, but all of it is small and visible. A JavaScript engine’s garbage collector pays for sharing everywhere, all the time; Rust pays only where you wrote Rc or RefCell.The .NET garbage collector pays for sharing everywhere, all the time; Rust pays only where you wrote Rc or RefCell. Plain values and borrows still cost nothing at run time.

    Common pitfalls

    Common pitfallRc<RefCell<T>> everywhere is a smell

    Porting an object graph from TypeScriptC# one class at a time tends to produce Rc<RefCell<T>> on every field. It compiles, but you’ve traded the compiler’s checks for run-time panics and lost track of who owns what. Before wrapping, ask whether one owner could hold the data and lend it out: a Vec<Node> that owns every node, with children stored as indices (usize) instead of pointers, often replaces a whole graph of Rcs. Keep Rc<RefCell<T>> for the few places where ownership really is shared.

    Common pitfallA RefCell borrow that lives too long panics

    A Ref or RefMut guard holds its borrow until it’s dropped. Keep one in a variable, then call a method that borrows the same RefCell mutably, and the program panics, as in panic.rs above. Keep guards short: use borrow_mut() inside a single statement, or put it in a small block, and don’t hold a guard across calls into other code that might use the same RefCell.

    Common pitfallRc::clone doesn't copy the value

    config.clone() on an Rc<Config> copies the pointer, not the Config, but it reads like a deep copy. Write Rc::clone(&config), which says what it does. If you do want a separate copy of the value, clone the value: (*config).clone(), which needs Config: Clone.

    Common pitfallArc doesn't make a value changeable

    Arc<T> shares ownership across threads, but like Rc it only gives out &T:

    use std::sync::Arc;
    
    fn main() {
        let scores: Arc<Vec<u32>> = Arc::new(Vec::new());
        scores.push(10);
    }

    Rust doesn't compile this: error E0596

    error[E0596]: cannot borrow data in an `Arc` as mutable
     --> main.rs:5:5
      |
    5 |     scores.push(10);
      |     ^^^^^^ cannot borrow as mutable
      |
      = help: trait `DerefMut` is required to modify through a dereference, but it is not implemented for `Arc<Vec<u32>>`

    Several threads changing one value need a lock inside: Arc<Mutex<Vec<u32>>>, covered in Threads, channels & shared state.

    Try it yourself

    Exercise: port this to Rust

    Port this scoreboard to Rust. Two players share one scoreboard and both add to its total. Use Rc for the sharing and the lightest interior mutability type that does the job.

    Starting code in TypeScript
    scoreboard.ts
    class Scoreboard {
      total = 0;
    }
    
    class Player {
      readonly name: string;
      readonly board: Scoreboard;
    
      constructor(name: string, board: Scoreboard) {
        this.name = name;
        this.board = board;
      }
    
      score(points: number): void {
        this.board.total += points;
        console.log(`${this.name} +${points}`);
      }
    }
    
    const board = new Scoreboard();
    const ada = new Player("Ada", board);
    const grace = new Player("Grace", board);
    ada.score(3);
    grace.score(5);
    ada.score(2);
    console.log(`total: ${board.total}`);
    Starting code in C#
    Scoreboard.cs
    var board = new Scoreboard();
    var ada = new Player("Ada", board);
    var grace = new Player("Grace", board);
    ada.Score(3);
    grace.Score(5);
    ada.Score(2);
    Console.WriteLine($"total: {board.Total}");
    
    class Scoreboard
    {
        public int Total { get; set; }
    }
    
    class Player(string name, Scoreboard board)
    {
        public void Score(int points)
        {
            board.Total += points;
            Console.WriteLine($"{name} +{points}");
        }
    }

    Expected output

    Ada +3
    Grace +5
    Ada +2
    total: 10
    Show a hint

    Each player needs a share of one scoreboard, so the players hold an Rc<Scoreboard>. The total is a number that changes behind a shared reference, so make it a Cell<u32> and update it with get and set.

    Show a solution
    use std::cell::Cell;
    use std::rc::Rc;
    
    struct Scoreboard {
        total: Cell<u32>,
    }
    
    struct Player {
        name: String,
        board: Rc<Scoreboard>,
    }
    
    impl Player {
        fn new(name: &str, board: &Rc<Scoreboard>) -> Self {
            Self {
                name: name.to_string(),
                board: Rc::clone(board),
            }
        }
    
        fn score(&self, points: u32) {
            self.board.total.set(self.board.total.get() + points);
            println!("{} +{points}", self.name);
        }
    }
    
    fn main() {
        let board = Rc::new(Scoreboard {
            total: Cell::new(0),
        });
        let ada = Player::new("Ada", &board);
        let grace = Player::new("Grace", &board);
        ada.score(3);
        grace.score(5);
        ada.score(2);
        println!("total: {}", board.total.get());
    }

    Rc::clone gives each player an owner of the same scoreboard without copying it. Rc only hands out shared references, so the total lives in a Cell<u32>, which allows set through &self. A Cell is enough here because u32 is Copy; a list or a map would need RefCell instead.

    Saved in this browser only.