I tried doing so with the Index trait, but it requires returning &Self::Output, so it cannot return a Result, but a &Result, which won’t work here. So, I implemented an example without the trait, requiring a method call instead, like arr.slice(0..5).
enum SliceError {
StartOutOfBounds,
EndOutOfBounds,
StartBiggerThanEnd
}
struct Wrap<'a, T: 'a>(&'a [T]);
impl<'a, T> Wrap<'a, T> {
fn slice(&self, range: Range<usize>) -> Result<&[T], SliceError> {
if range.start >= self.0.len() {
Err(SliceError::StartOutOfBounds)
} else if range.end > self.0.len() {
Err(SliceError::EndOutOfBounds)
} else if range.start > range.end {
Err(SliceError::StartBiggerThanEnd)
} else {
unsafe {
Ok(slice::from_raw_parts (
self.0.as_ptr().offset(range.start as isize),
range.end - range.start
))
}
}
}
}
playground