Rc<Vec<T>> with only 'one level of indirection'?

Vec<T> only has 'one level' of indirection in the sense of:

  1. We have the Vec object.
  2. It points to somewhere no the heap, we do one heap access.

Rc<Vec<T>> , in my current understanding, has 'two levels' of indirection in the sense of:

  1. We have a Rc object.
  2. We do one heap access to get the Vec<T> object.
  3. We then do another heap access to read the actual element.

Question: is there some object that behaves like a Rc<Vec<T>>, but, when reading elements, only has 'one level' of indirection ?

If you don’t need to grow/shrink the contents, you can use an Rc<[T]>. This seems likely, since you weren’t asking about Rc<RefCell<Vec<T>>>

4 Likes

You do know, that you cannot mutate the Vec through Rc? You may be able to mutate the elements of the vector with interior mutability, but you're unable to safely change the length or capacity of the vector or swap it.

Well, there’s Rc::try_unwrap() and Rc::make_mut() which enable it under limited circumstances.

For running code pre- and post-shared ownership, indeed. Not while sharing ownership.

Sorry for not clarifying in original post. In this particular case, the only ops I need are:

Vec<T> -> Weird_Rc_Vec<T> and

Weird_Rc_Vec<T> :: get_item(i: usize)

i.e. after creation, the only op is reading.

(Technically you may be using Rc<Vec<T>> not to necessarily share, but rather to lazily clone / get CoW semantics (Rc::make_mut), which may thus happen while "sharing").

type WeirdRcVec<T> = Rc<[T]>,

using <Rc<[T]> as From<Vec<T>>>::from() to construct it.

1 Like