How to create a Rc> (or convert to it from a Vec)?

⚓ Rust    📅 2025-08-13    👤 surdeus    👁️ 4      

surdeus

I want to create a Rc<RefCell<[Value]>>. (a reference-counted shared pointer to a dynamically allocated fixed-size array on the heap, that I can mutate). How can I create such an object? (either by creating one filled with a default value, or by creating one from a Vec)?

From<Vec<T>> is implemented for Box<[T]> and for Rc<[T]> so I can easily create those two types by calling .into(), but not Rc<RefCell<[T]>>

use std::rc::Rc;
use std::cell::RefCell;
fn main() {
    let a: Vec<i32> =vec![1; 32];
    
    //let b: Box<[i32]> = a.into(); // works
    
    //let b: Rc<[i32]> = a.into(); // works
    
    //let b: Rc<RefCell<[i32]>> = a.into(); // doesn't work, From trait not implemented

    // doesn't work, because a[..], with type [i32], is unsized
    let b: Rc<RefCell<[i32]>> = Rc::new(RefCell::new(a[..]));
}

(In the end, I created a Rc<[RefCell<Value>]> instead, but I'm still wondering how to do what I initially wanted.)

3 posts - 3 participants

Read full topic

🏷️ Rust_feed