尝试实现借用某些数据并拥有其他数据的迭代器时出现编译错误



我正在尝试实现一个迭代器:

struct MyIterator<'a> {
    s1: &'a str,
    s2: String,
    idx: usize,
}
impl<'a> MyIterator<'a> {
    fn new(s1: &str) -> MyIterator {
        MyIterator {
            s1: s1,
            s2: "Rust".to_string(),
            idx: 0,
        }
    }
}
impl<'a> Iterator for MyIterator<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        self.idx += 1;
        match self.idx {
            1 => Some(self.s1),
            2 => Some(&self.s2),
            _ => None,
        }
    }
}

我收到这个非常详细的错误消息,但我不知道如何修复代码:

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> srcmain.rs:39:23
   |
39 |             2 => Some(&self.s2),
   |                       ^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 34:5...
  --> srcmain.rs:34:5
   |
34 | /     fn next(&mut self) -> Option<Self::Item> {
35 | |         self.idx + 1;
36 | |
37 | |         match self.idx {
...  |
41 | |         }
42 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> srcmain.rs:39:23
   |
39 |             2 => Some(&self.s2),
   |                       ^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 31:1...
  --> srcmain.rs:31:1
   |
31 | / impl<'a> Iterator for MyIterator<'a> {
32 | |     type Item = &'a str;
33 | |
34 | |     fn next(&mut self) -> Option<Self::Item> {
...  |
42 | |     }
43 | | }
   | |_^
note: ...so that types are compatible (expected std::iter::Iterator, found std::iter::Iterator)
  --> srcmain.rs:34:46
   |
34 |       fn next(&mut self) -> Option<Self::Item> {
   |  ______________________________________________^
35 | |         self.idx + 1;
36 | |
37 | |         match self.idx {
...  |
41 | |         }
42 | |     }

为什么s2一生不是简单地'a

返回

的值的类型为 Option<&'a str> ,但'a不会使MyIterator<'a>保持活动状态,因此它可能超出范围,并且包含的s2: String。 所以'a根本无法s2活着。 (它只会让s1活着,如果你写了fn new(s1: &'a str) -> MyIterator<'a>,会更容易看出来)

此外,Iterator特征的设计方式是,您永远无法next函数中返回对存储在Iterator本身中的内容的引用。

相反,您可以创建一个存储值的类型,并为对该值的引用实现IntoIterator(使用包含对存储对象的引用的单独迭代器类型)。

最新更新