I have types that compactly represent a sequence of elements by compressing multiple elements into a single number. Since all my elements are of the same size, I can index into this sequence, and I can take subsequences. Therefore I would like to implement Index<Range<usize>> to allow indexing with the [a..b] operator. Below is a simplified example.
use std::ops::{Index, Range};
struct VecWrapper {
vec: Vec<i32>,
}
struct SliceWrapper {
slice: [i32],
}
impl Index<Range<usize>> for VecWrapper {
type Output = SliceWrapper;
fn index(&self, index: Range<usize>) -> &Self::Output {
&SliceWrapper {slice: self.vec[index]}
}
}
This sadly does not compile, but throws the following error:
Compiling playground v0.0.1 (/playground)
error[E0277]: the size for values of type `[i32]` cannot be known at compilation time
--> src/lib.rs:15:10
|
15 | &SliceWrapper {slice: self.vec[index]}
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: within `SliceWrapper`, the trait `Sized` is not implemented for `[i32]`
= note: required because it appears within the type `SliceWrapper`
= note: structs must have a statically known size to be initialized
Is it possible to make this code compile somehow, such that SliceWrapper is not Sized, but can still be returned in the index method?