I'm running into an issue with lifetimes in rust that I'm having trouble figuring out. I've tried a lot of tweaks to the below but I keep introducing new errors. I want index to return a Vector object.
I have:
struct Matrix<T> {
num_rows: i32,
num_cols: i32,
data: Vec<T>
}
struct Vector<T> {
data: Vec<T>
}
And I'm trying to do
impl<T: Clone> Index<usize> for Matrix<T> {
type Output = Vector<T>;
fn index(&self, i: usize) -> &Vector<T> {
let index = i as i32;
let start = (index * &self.num_cols) as usize;
let end = (((index + 1) * &self.num_cols) - 1) as usize;
let data_slice = &self.data[start..end];
let data = data_slice.to_vec();
let vector_temp = Vector::<T>::new(data);
return &vector_temp;
}
}
But I'm getting
error: `vector_temp` does not live long enough
--> src\main.rs:45:17
|
45 | return &vector_temp;
| ^^^^^^^^^^^ does not live long enough
46 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 38:44...
--> src\main.rs:38:45
|
38 | fn index(&self, i: usize) -> &Vector<T> {
| ^
error: aborting due to previous error
error: Could not compile `hello_world`.
I haven't fully grokked lifetimes in rust yet so was hoping someone could help me out. Thanks!