【问题标题】:Strange compile error with lifetime notation: "expected `:`, found `>`"带有生命周期符号的奇怪编译错误:“预期的`:`,发现`>`”
【发布时间】:2019-01-07 03:25:35
【问题描述】:

我已经定义了一个这样的结构和方法:

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
    }
}

编译时出现错误

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

但是,按照它的要求做并将违规行更改为let mut lexer = Lexer&lt;'a:&gt; { 是没有意义的,重新编译确认这确实是不正确的。

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

我不确定编译器为什么会抱怨,但我只能说生命周期符号对我来说看起来不错。

Rust Playground

【问题讨论】:

  • 您的代码无法编译,因为0 不是字符,这个问题只是一个语法错误。你必须写Lexer::&lt;'a&gt;或更短的Lexer(这也不是MCVE,因为你可以省略Lexer中的所有字段,只添加需要&lt;'a&gt;的内容,例如PhantomData
  • Lexer&lt;'a 可以是表达式的开头,将名为 Lexer 的变量与像 'a: loop { break 'a 4; } 这样的命名循环表达式进行比较。 Example
  • @hellow 0 不是字符,但编译器不会给出错误,直到相关错误得到解决,所以我没有抓住它。此代码还有(许多)其他错误,但在修复相关错误之前,编译器看不到任何错误。不管怎样,我已经更新了我的问题。

标签: compiler-errors rust lexer


【解决方案1】:

我刚刚意识到,构造函数不需要生命周期。

正确的记法是

let mut lexer = Lexer {

不是

let mut lexer = Lexer<'a> {

【讨论】:

  • 为什么是mut? ;)
  • 代码中不需要原样。在我的实际程序中,词法分析器在构造之后但在返回之前进行了修改。我为这个问题删除了它,因为它无关紧要。我将在这里更新我的代码以更好地反映这一点。
  • 这很明显不用担心^^
猜你喜欢
  • 2014-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2014-08-29
相关资源
最近更新 更多