Code Logo

Shared Mutability with Rc RefCell

Published at25 Jul 2026
Rust Data Structures Hard 0 views
Like0

Write a Rust function that uses Rc> to share a single mutable value through multiple handles. The function takes a count n and a value, creates an Rc>, clones the Rc n times, mutates the value through one handle, and returns a vector where each element is the value observed through each handle.

Rc (Reference Counting) enables multiple ownership of the same data. RefCell provides interior mutability — the ability to mutate data through a shared reference. Together, Rc> is the standard pattern in Rust for shared mutable state in single-threaded contexts. Rc handles cloning, RefCell handles mutation at runtime with borrow checking.

The combination of Rc and RefCell is powerful but requires runtime borrow checking. RefCell::borrow_mut() panics if the value is already borrowed, enforcing Rust's borrowing rules at runtime instead of compile time. This is essential for graph structures, caches, and other patterns where shared mutability is needed.

Time complexity is O(n) for cloning Rc handles and reading values. Space complexity is O(n) for the result vector. The Rc cloning is O(1) as it only increments the reference count; the actual data is not copied.

Edge cases include n = 0 (return empty vector), negative values, and ensuring all handles reflect the mutation because they share the same inner RefCell via Rc.

Example Input & Output

Example 1
Input
1,42
Output
[42]
Explanation

Single handle

Example 2
Input
3,-5
Output
[-5,-5,-5]
Explanation

Negative value across three handles

Example 3
Input
2,10
Output
[10,10]
Explanation

Two handles both see 10

Example 4
Input
3,7
Output
[7,7,7]
Explanation

Three Rc handles all reflect the mutation

Example 5
Input
4,0
Output
[0,0,0,0]
Explanation

Four handles all see 0

Algorithm Flow

Recommendation Algorithm Flow for Shared Mutability with Rc RefCell
Recommendation Algorithm Flow for Shared Mutability with Rc RefCell

Solution Approach

use std::cell::RefCell;
use std::rc::Rc;

fn solution(n: i32, value: i32) -> Vec<i32> {
    let data = Rc::new(RefCell::new(0));
    let mut handles = vec![];

    for _ in 0..n {
        handles.push(Rc::clone(&data));
    }

    *data.borrow_mut() = value;

    handles.iter().map(|h| *h.borrow()).collect()
}

Best Answers

rust - Approach 1
use std::cell::RefCell;
use std::rc::Rc;

fn solution(n: i32, value: i32) -> Vec<i32> {
    let data = Rc::new(RefCell::new(0));
    let mut handles = vec![];

    for _ in 0..n {
        handles.push(Rc::clone(&data));
    }

    *data.borrow_mut() = value;

    handles.iter().map(|h| *h.borrow()).collect()
}