Return reference to data inside refcell?

Hello,
I have a RefCell<Vec<T>>, and I’m trying to find a way to return a reference (ideally an &, but Ref<T> works too) to an element at a given index inside the vector. I’ve seen things like this and this, but I’m unsure on how to adapt it to a situation where I have to return a reference to an element inside a vector.

use std::cell::{RefCell, Ref};

fn index(vec: &RefCell<Vec<T>>, index: usize) -> Ref<T> {
    let vec = vec.borrow();
    Ref::map(vec, |x| &x[index])
}

You can do something similar with RefMut if you need it.

5 Likes

Thanks!

Is there any way I can get a reference (not a “Ref”, but an “&”) out of that?

If you try this, then the point of RefCell is broken. The reason we return a Ref<'a, T> instead of &T is that without giving the caller a Ref, the lock on the RefCell will be broken before the reference is dropped. Think of a RefCell like a mutex:
If you call .lock on it, you want to make sure noone else can touch the data inside, therefore returning a reference from .lock would have no way to tell the Mutex that it’s okay to unlock it.

2 Likes

Oh, OK, makes sense. Thanks!

Note that if you’re the sole owner of that RefCell, you can use get_mut to get an unguarded reference to the underlying data.

Yeah, I’m not the sole owner of the refcell. The map approach worked, though (krishnasannasi’s approach)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.