Iterator error E0207

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=23abce333176cd9610eb6ec2aa65be19

The playground example produces the error

error[E0207]: the lifetime parameter `'a` is not constrained by the impl trait, self type, or predicates
  --> src/main.rs:25:6

For more information about this error, try `rustc --explain E0207`.

There are no generics involved; this is a complaint about lifetime issues only. The explanation for error E0207 is focused on a similar error involving generics.

Motivation: The goal is to put a reference to a data item into a struct, then use a function associated with the struct as an iterator over the data item, returning references to parts of the original data item.. My goal is to parse a message buffer with multiple messages, and generate data structures of the parse without allocating on the heap. Most of the time, the parsed message is acted upon and discarded; sometimes it has to be cloned and saved.

I'm doing this now with a callback function, but I wanted to do it with an iterator, which would simplify the control flow.

The example is just something simple to figure out how to do this in Rust.

This impl block fixes the issue:

impl<'a> Iterator for Words<'a> {
    type Item = &'a[u8];
    /// Get next word or None
    fn next(&mut self) -> Option<&'a [u8]> { ... }
}

Playground


Lifetime annotations are generics. The error message is complaining that 'a isn't used in the type name for the block, and so doesn't know which program region 'a refers to:

impl<'a> Iterator for Words<'_> { ... }

Additionally, these lifetime annotations need to match. Because Item is &'a [u8], the return type of next() needs to be Option<&'a [u8]>:

type Item = &'a[u8];
fn next<'b>(&'b mut self) -> Option<&'b [u8]>
1 Like