I have a piece of code:
#[derive(Clone, Copy, Debug)]
struct Ab {
a: u32,
b: u32,
}
#[derive(Clone, Copy, Debug)]
struct MeAb {
a: u32,
b: [Ab; 5],
}
struct Iter<'a> {
idx: u32,
inner: &'a mut MeAb,
}
impl<'a> Iter<'a> {
fn new(inner: &'a mut MeAb) -> Self {
Self { idx: 0, inner }
}
}
impl MeAb {
fn iter(&mut self) -> Iter {
Iter::new(self)
}
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a mut Ab;
fn next(&mut self) -> Option<Self::Item> {
if self.idx < 5 {
let ret = &mut self.inner.b[self.idx as usize];
self.idx += 1;
return Some(ret)
} else {
return None
}
}
}
fn main() {
let mut cc = MeAb {
a: 0,
b: [Ab { a: 1, b: 2 }; 5]
};
for i in cc.iter() {
i.a = 5;
println!("i {:?}", i);
}
println!("cc {:?}", cc);
}
Now, There are the following errors:
error: lifetime may not live long enough
--> kernel/init/src/main.rs:37:24
|
30 | impl<'a> Iterator for Iter<'a> {
| -- lifetime `'a` defined here
...
33 | fn next(&mut self) -> Option<Self::Item> {
| - let's call the lifetime of this reference `'1`
...
37 | return Some(ret)
| ^^^^^^^^^ method was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
error: could not compile `init` due to previous error
What should I do to return a mutable reference in an iterator?