【发布时间】:2022-12-16 10:12:47
【问题描述】:
我正在尝试在向量上编写一个可变迭代器,但我无法弄清楚编译器试图告诉我什么。这是我的实现
struct IterMut<'a> {
vec: &'a mut Vec<u32>,
index: usize,
}
impl<'a> Iterator for IterMut<'a> {
type Item = &'a mut u32;
fn next(&mut self) -> Option<Self::Item> {
let item = if self.index < self.vec.len() {
Some(&mut self.vec[self.index])
} else {
None
};
self.index += 1;
item
}
}
编译器错误是:
error: lifetime may not live long enough
--> src/main.rs:60:9
|
48 | impl<'a> Iterator for IterMut<'a> {
| -- lifetime `'a` defined here
...
51 | fn next(&mut self) -> Option<Self::Item> {
| - let's call the lifetime of this reference `'1`
...
60 | item
| ^^^^ associated function was supposed to return data with lifetime `'a` but it is returning data with lifetime `'1`
非可变版本编译和工作。
struct Iter<'a> {
vec: &'a Vec<u32>,
index: usize,
}
impl<'a> Iterator for Iter<'a> {
type Item = &'a u32;
fn next(&mut self) -> Option<Self::Item> {
let item = if self.index < self.vec.len() {
Some(&self.vec[self.index])
} else {
None
};
self.index += 1;
item
}
}
Here is a playground link with the code to try out.
任何帮助是极大的赞赏。
【问题讨论】: