I want to keep an Holded
instance, but I can't since it's in an array. How can I do to 'extract' this instance from the array and keep it in an Object
instance ? (In my original code, I don't have array but iterators). Here is the equivalent code :
struct Holded {
value: u8,
}
struct Holder;
impl Holder {
pub fn get(&self) -> [Holded; 2] {
[Holded { value: 0 }, Holded { value: 1 }]
}
}
struct Object<'a> {
holded: &'a Holded,
}
fn main() {
let holder = Holder;
let obj = work(&holder).unwrap();
println!("{}", obj.holded.value);
}
fn work(holder: &Holder) -> Option<Object> {
let mut obj: Object;
let array = holder.get();
for h in array.into_iter() {
if h.value == 1u8 {
obj = Object { holded: h };
return Some(obj);
}
}
None
}
The error message:
error: `array` does not live long enough
--> src/main.rs:28:14
|
28 | for h in array.into_iter() {
| ^^^^^ does not live long enough
...
36 | }
| - borrowed value only lives until here
|
note: borrowed value must be valid for the anonymous lifetime #1 defined on the block at 24:43...
--> src/main.rs:24:44
|
24 | fn work(holder: &Holder) -> Option<Object> {
| ^