0

I'm learning to write iterators in Rust but am hitting an "expected colon" issue where I would not expect a colon to even make sense. Maybe it has to do with lifetimes? References? I tried making a regular function that returns the same data in the same way and it worked (or at least got past this error message) so it appears to be special to the Iterator trait... but I can't work out why.

struct LogEntry;

pub struct LogIter<'a> {
    index0: bool,
    first: LogEntry,
    iter: ::std::slice::Iter<'a, LogEntry>,
}

impl<'a> Iterator for LogIter<'a> {
    type Item = &'a LogEntry;
    fn next(&mut self) -> Option<Self::Item> {
        self.index0 = false;
        match self.index0 {
            true => Some(&'a self.first),
            false => self.iter.next(),
        }
    }
}

It is meant to return first and then iterate normally but I cannot figure out why or how I could possibly fit a colon in here.

error: expected `:`, found keyword `self`
  --> src/lib.rs:14:30
   |
14 |             true => Some(&'a self.first),
   |                              ^^^^ expected `:`
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Lemma Prism
  • 371
  • 1
  • 2
  • 8
  • What resources did you follow that led you to think that `&'a self.first` is valid syntax? – Shepmaster Aug 08 '19 at 02:26
  • _Ooh..._ So that's something that led me astray. Thank you, I must have been generalizing from type signatures. Okay, so in that case what I needed to figure out is how to disambiguate lifetimes so Rust can infer the correct one. (I now get, `cannot infer an appropriate lifetime for borrow expression due to conflicting requirements`.) – Lemma Prism Aug 08 '19 at 02:45

1 Answers1

3

Your question is solved by pointing out that &'a foo isn't a valid expression. It doesn't make sense to specify a lifetime when taking a reference as the compiler will automatically ensure the correct lifetimes.

You want to use Some(&self.first).


Your problem is addressed by How do I write an iterator that returns references to itself?.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366