Search code examples
compiler-errorsrustlexer

Strange compile error with lifetime notation: "expected `:`, found `>`"


I have defined a struct and method like so:

struct Lexer<'a> {
    input: String,
    pos: CharIndices<'a>,
    next_pos: Peekable<CharIndices<'a>>,
    ch: char,
}

impl<'a> Lexer<'a> {
    pub fn new(input: String) -> Lexer<'a> {
        let mut lexer = Lexer<'a> {
            input,
            pos: input.char_indices(),
            next_pos: input.char_indices().peekable(),
            ch: char::from(0 as u8),
        };

        lexer
    }
}

When compiling I get the error

error: expected `:`, found `>`
  --> src/lexer/mod.rs:15:33
   |
15 |         let mut lexer = Lexer<'a> {
   |                                 ^ expected `:`

However, doing as it asks and changing the offending line to let mut lexer = Lexer<'a:> { makes no sense and recompiling confirms that this is indeed incorrect.

error: expected `while`, `for`, `loop` or `{` after a label
  --> src/lexer/mod.rs:15:34
   |
15 |         let mut lexer = Lexer<'a:> {
   |                                  ^ expected `while`, `for`, `loop` or `{` after a label

I'm not sure why the compiler is complaining and as best I can tell the lifetime notation looks fine to me.

Rust Playground


Solution

  • I have just realized, there is no need for a lifetime on the constructor.

    The correct notation is

    let mut lexer = Lexer {
    

    not

    let mut lexer = Lexer<'a> {