3

I have a struct A with a string field string:

struct A<'a> {
    string: String,
    //some other field which needs the lifetime specifier
}

and I want to implement Iterator to return a slice of string.

impl<'a> Iterator for A<'a> {
    type Item = &'a str;
    fn next(&mut self) -> Option<Self::Item> {
        //do something to get the index `x` and `y`
        return Some(&self.string[x .. y]);
    }
}

The compiler says:

error[E0495]: cannot infer an appropriate lifetime for lifetime parameter in function call due to conflicting requirements
  --> src/main.rs:11:22
   |
11 |         return Some(&self.string[x .. y]);
   |                      ^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body at 8:5...
  --> src/main.rs:8:5
   |
8  | /     fn next(&mut self) -> Option<Self::Item> {
9  | |         let x = 1;
10 | |         let y = 2;
11 | |         return Some(&self.string[x .. y]);
12 | |     }
   | |_____^
note: ...so that reference does not outlive borrowed content
  --> src/main.rs:11:22
   |
11 |         return Some(&self.string[x .. y]);
   |                      ^^^^^^^^^^^
note: but, the lifetime must be valid for the lifetime 'a as defined on the impl at 6:6...
  --> src/main.rs:6:6
   |
6  | impl<'a> Iterator for A<'a> {
   |      ^^
   = note: ...so that the types are compatible:
           expected std::iter::Iterator
              found std::iter::Iterator

And I tried:

fn next<'b: 'a>(&'b mut self) -> Option<&'b str> {
        //do something to get the index `x` and `y`
        return Some(&self.string[x .. y]);
    }

The compiler says:

error[E0195]: lifetime parameters or bounds on method `next` do not match the trait declaration
 --> src/main.rs:8:12
  |
8 |     fn next<'b: 'a>(&'b mut self) -> Option<&'b str> {
  |            ^^^^^^^^ lifetimes do not match method in trait
trent
  • 25,033
  • 7
  • 51
  • 90
Evian
  • 1,035
  • 1
  • 9
  • 22
  • 1
    tl;dr the duplicate: `Iterator` doesn't support streaming iterators; you'll have to do without it. But there is still plenty you can do with a streaming API; you just don't get the neat `for` loop syntax or standard iterator adapters (although there are "streaming versions" of most). – trent Aug 20 '19 at 03:35
  • 1
    `'a` is not an appropriate lifetime for your string. That's the lifetime of a field of your struct that is not related. The issue, is that there is no way to express the lifetime of your struct. – Boiethios Aug 20 '19 at 07:11

0 Answers0