2

I have these structs

pub struct Lexer {
    input: Vec<char>,
    // ...
}

pub struct Token<'a> {
    pub t: TokenType,
    pub literal: Literal<'a>,
}

pub enum Literal<'a> {
    Chars(&'a [char]), // here borrows from the origin input string in Lexer
    // ...
}


The field literal of Token with type Literal has some slice borrowing directly from origin input string in the input field of struct Lexer. There is a method of Lexer called next_token like this:

pub fn next_token(&mut self) -> Token

I'm intending to let Lexer implement the traitor Iterator like :

impl<'a> Iterator for Lexer {
    type Item = Token<'a>;

    fn next(&mut self) -> Option<Self::Item> {

        let t = self.next_token();
        Some(t)
    }

But get errors like

the lifetime parameter 'a is not constrained by the impl trait, self type, or predicates"

How can I set the correct lifetime and implement Iterator trait for Lexer?

hliu
  • 1,015
  • 8
  • 16
  • 3
    You can't, the `Iterator` trait doesn't allow borrowing from it's implementor. You should instead have an `IntoIterator` implementation returning a helper struct. – cafce25 Jun 10 '23 at 16:38

0 Answers0