1

I am trying to implement multiple "slices" over a shared array of objects. My solution is to morally make a

struct MySlice<T>{ shared_data: Rc<[T]> , beg: usize, len: usize }

I want to be able to implement both

  • impl From<Vec<T>> for MySlice<T> { /* ?? */ }
  • and fn get_mut_slice(&mut MySlice<T>) -> &mut [T] which returns the entire underlying slice.

With the above implementation I can get the former but not the latter. I tried modifying the type into

struct MySlice1<T>{ shared_data: Rc<RefCell<[T]>> , beg: usize, len: usize }

But I couldn't get it to work. Is there an idiomatic way to get both?

fakedrake
  • 6,528
  • 8
  • 41
  • 64
  • Can you explain how you got the latter with `RefCell`? [I couldn't](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=848bea893150af8d6378c9f485ac5081). – Chayim Friedman Jun 08 '22 at 21:21
  • You are right, it was a stupid mistake. Actually I cant get the latter either (I edited the question) – fakedrake Jun 08 '22 at 21:32

1 Answers1

1

The first can be done by storing a Rc<RefCell<Vec<T>>>. I don't think this can be done with a slice, unfortunately.

The second cannot exist as-is. If you have shared ownership, and you want to get a mutable reference, you have to make sure nobody else will use the value as long as the mutable reference is active. This can only be done with a guard. You can change its signature to:

pub fn get_mut_slice(&mut MySlice<T>) -> RefMut<'_, [T]>

Then:

pub fn get_mut_slice(&mut self) -> RefMut<'_, [T]> {
    RefMut::map(self.shared_data.borrow_mut(), |s| {
        &mut s[self.beg..][..self.len]
    })
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77