I defined two struct
s like these:
#[derive(Debug)]
struct Slices<'a> {
intervals: &'a[u32]
}
#[derive(Debug)]
struct NumbersWithSlices<'a> {
numbers: Vec<u32>,
slices: Vec<Slices<'a>>
}
and I managed to write a main
like this:
fn main() {
let raw: Vec<u32> = vec![0,1,2,3,4,5,6,7,8,9];
let mut sf = NumbersWithSlices {
numbers: raw,
slices: vec![]
};
sf.slices.push(Slices{intervals: &sf.numbers[0..1]});
sf.slices.push(Slices{intervals: &sf.numbers[1..3]});
println!("{:?}", sf.slices[1].intervals[0]);
}
which works as I expected.
Now I would like to implement a new
function fro NumbersWithSlices
which mimics what I did in main
: I end up with
impl<'a> NumbersWithSlices<'a> {
fn new(numbers: Vec<u32>) -> Self {
let mut res = Self {
numbers,
slices: vec![]
};
let start_idx = 0; // for the moment
let stop_idx = 1; // for the moment
res.slices.push(Slices{intervals: &res.numbers[start_idx..stop_idx]});
return res;
}
}
This code gives me an compilation error
error[E0505]: cannot move out of `res` because it is borrowed
--> src/main.rs:25:16
|
13 | impl<'a> NumbersWithSlices<'a> {
| -- lifetime `'a` defined here
...
16 | let mut res = Self {
| ------- binding `res` declared here
...
23 | res.slices.push(Slices{intervals: &res.numbers[start_idx..stop_idx]});
| ----------- borrow of `res.numbers` occurs here
24 |
25 | return res;
| ^^^
| |
| move out of `res` occurs here
| returning this value requires that `res.numbers` is borrowed for `'a`
error[E0515]: cannot return value referencing local data `res.numbers`
--> src/main.rs:25:16
|
23 | res.slices.push(Slices{intervals: &res.numbers[start_idx..stop_idx]});
| ----------- `res.numbers` is borrowed here
24 |
25 | return res;
| ^^^ returns a value referencing data owned by the current function
I think I'm able to understand the error, but I cannot find how to write the correct code to get the result I want, just as written in main
function.