Rc and RefCell

Rc for single-thread shared ownership and RefCell for runtime borrow checks, including try_borrow instead of a panic message.

テーマページの本文は現在英語です。

Rc<T> is a reference-counted pointer for single-thread sharing. Rc::clone increments the strong count and does not clone T. Official documentation states that Rc is not Send and is not Sync; those bounds fail at compile time if you try to move an Rc to another thread or share it across threads. Use Arc when you need shared ownership across threads.

RefCell<T> moves Rust's borrow rules to runtime on one thread. borrow and borrow_mut panic if the dynamic borrow conflicts. The examples use try_borrow and try_borrow_mut and print is_err, so they do not depend on panic message text. Rc<RefCell<T>> is the usual single-thread shared mutable pair; it is still not Send or Sync.

Examples were compiled with rustc 1.90.0 using --edition=2024 and run as a plain binary. See the Rust 1.90.0 documentation for the complete API.

Rust reference overview →

API index

APISummary
Rc::new, Rc::clone, Rc::strong_countShare ownership of T on one thread. Cloning an Rc does not clone T, and the type cannot be sent to another thread.
RefCell::new, RefCell::borrow_mut, RefCell::try_borrow, RefCell::try_borrow_mut, RefCell::borrowCheck a dynamic borrow with try_borrow instead of panicking. Conflicts are reported as Err while a mutable guard is still in scope.

Rc

Rc::new wraps a value. Rc::clone (or .clone()) points at the same allocation and raises the strong count to 2. Dereferencing either handle yields 5. The type is for one thread: an Rc is not Send and not Sync, in contrast to Arc on the sync page.

Rc::new, Rc::clone, Rc::strong_count

pub fn new(value: T) -> Rc<T>
pub fn clone(this: &Rc<T>) -> Rc<T>
pub fn strong_count(this: &Rc<T>) -> usize

Share ownership of T on one thread. Cloning an Rc does not clone T, and the type cannot be sent to another thread.

ParameterDescription
value / thisThe owned value, or an existing Rc to clone. clone shares the allocation.

Returns: A new Rc handle. strong_count is the number of strong handles still alive.

  • This example stays on the main thread because Rc is not Send. Crossing threads is a compile error, not something this binary can demonstrate by running.
rust
use std::rc::Rc;

fn main() {
    let first = Rc::new(5);
    let second = Rc::clone(&first);
    println!("{} {}", Rc::strong_count(&first), *second);
}

Expected output

2 5

Related: Arc and Mutex

Official documentation →

RefCell and try_borrow

While a borrow_mut guard is alive, try_borrow and try_borrow_mut both return Err. After the guard is dropped, borrow succeeds and the value is 2. The example prints is_err rather than the BorrowError display string or a panic from borrow(). Combining Rc with RefCell lets two handles mutate the same i32 on one thread; the final value is 5.

RefCell::new, RefCell::borrow_mut, RefCell::try_borrow, RefCell::try_borrow_mut, RefCell::borrow

pub const fn new(value: T) -> RefCell<T>
pub fn borrow(&self) -> Ref<'_, T>
pub fn borrow_mut(&self) -> RefMut<'_, T>
pub fn try_borrow(&self) -> Result<Ref<'_, T>, BorrowError>
pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, BorrowMutError>

Check a dynamic borrow with try_borrow instead of panicking. Conflicts are reported as Err while a mutable guard is still in scope.

ParameterDescription
valueThe value stored in the cell. For shared mutation on one thread, wrap the cell in an Rc.

Returns: borrow and borrow_mut return RAII guards that dereference to T. The try_ methods return Result, with Err if the requested borrow conflicts with a live guard.

Errors and panics

  • BorrowError / BorrowMutError — Returned by try_borrow and try_borrow_mut when the cell is already borrowed in a conflicting way. borrow and borrow_mut panic in those cases; this page uses the try_ methods so the output does not depend on panic text.
  • The try_borrow checks run while borrow_mut is still in scope. After that inner block ends, the later borrow is allowed.
rust
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let cell = RefCell::new(1);
    {
        let mut borrow = cell.borrow_mut();
        *borrow += 1;
        println!("{}", cell.try_borrow().is_err());
        println!("{}", cell.try_borrow_mut().is_err());
    }
    println!("{}", *cell.borrow());

    let shared = Rc::new(RefCell::new(0));
    let alias = Rc::clone(&shared);
    *alias.borrow_mut() += 4;
    *shared.borrow_mut() += 1;
    println!("{}", *shared.borrow());
}

Expected output

true
true
2
5

Related: Rc

Official documentation →