I'm trying to wrap a slice in a struct so that I will be able to instantiate the struct mutably or immutably. Here's a minimal example:
use std::ops::{ Index, IndexMut }; struct Test<'a, T: 'a> { inner: &'a[T] } impl<'a, T: 'a> Test<'a, T> { fn new (inner: &'a[T]) -> Self { Test { inner: inner } } } impl<'a, T> Index<usize> for Test<'a, T> { type Output = T; fn index (&self, i: usize) -> &T { &self.inner[i] } } impl<'a, T> IndexMut<usize> for Test<'a, T> { fn index_mut (&mut self, i: usize) -> &mut T { &mut self.inner[i] } } fn main() { let store = [0; 3]; let test = Test::new (&store); println!("{}", test[1]); let mut mut_store = [0; 3]; let mut mut_test = Test::new (&mut mut_store); mut_test[1] = 42; println!("{}", mut_test[1]); } This doesn't compile: "cannot borrow immutable indexed content self.inner[..] as mutable".
I could get it to compile by changing the definition of inner to be of type &'a mut[T], but then inner is mutable even when I don't need it to be (in the above example, I must then declare store as mutable too even though test is immutable).
Is there a way to make it so that the mutability of inner follows the mutability of the Test instance?