Box<[T]>` cannot be mutably indexed by `I`

On the code below, I'm trying to cast the interior of the Box to something that can be indexable, both mutably and not.

use core::ops::IndexMut;
use std::slice::SliceIndex;
use core::ops::Index;

pub trait M<T, I: SliceIndex<[T], Output = T>>:
	AsRef<[T]> + AsMut<[T]> + Index<I, Output = T> + IndexMut<I>
{}

impl<T, I, V> M<T, I> for V
where
	V: AsRef<[T]> + AsMut<[T]> + Index<I, Output = T> + IndexMut<I>,
	I: SliceIndex<[T], Output = T>,
{}

fn allocate_default<T: Default + Clone, I>(size: usize) -> Box<dyn M<T, I> + 'static> 
where
	I: SliceIndex<[T], Output = T>,
{
	let s = vec![T::default(); size];
	let s = s.into_boxed_slice();
	Box::new(s)
}

Why is it complaining that Box does not implement IndexMut? Shouldn't it complain about the interior not implementing it?

I think it may have something to do with interior mutability of Box maybe, so I tried fn allocate_default<T: Default + Clone, I>(size: usize) -> RefCell<dyn M<T, I> + 'static> but then I get

error[E0277]: the size for values of type `(dyn M<T, I, Output = T> + 'static)` cannot be known at compilation time

I want to return something that implement M, not the actual vector.

Box doesn't provide interior mutability.

Anyway, the problem is literally that Box<[T]> isn't indexable. You are trying too hard to perform conversions. Just leave the vector as-is. Accordingly, this compiles.

I totally forgot that I had a boxed slice, I thought I was returning a Box<Vec<>>

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.