I have two (very large) arrays foo
and bar
of the same type. To be able to write some nice code, I would like to obtain a read-only slice, result
For n arrays, you can implement it using a Vec
like below:
use std::ops::Index;
struct VecSlice<'a, T: 'a>(Vec<&'a [T]>);
impl<'a, T> Index for VecSlice<'a, T> {
type Output = T;
fn index(&self, mut index: usize) -> &T {
for slice in self.0.iter() {
if index < slice.len() {
return &slice[index];
} else {
index -= slice.len();
}
}
panic!("out of bound");
}
}
And then access it like an array, just don't go out of bound.
fn main() {
let a1 = [0, 1, 2];
let a2 = [7, 8, 9];
let a = VecSlice(vec!(&a1, &a2));
println!("{}", a[4]);
}
This prints out
8