Compiler errors 编译错误

Compiler errors 编译错误,compiler-errors,rust,borrow-checker,Compiler Errors,Rust,Borrow Checker,我试图通过写一个简单的词法来学习生锈。这是我到目前为止所拥有的 use std::fs::File; use std::io::Read; use std::str::Chars; pub struct Lexer<'a> { file_name: String, file_contents: String, iterator: Option<Chars<'a>>, } impl<'a> Lexer<'a>

我试图通过写一个简单的词法来学习生锈。这是我到目前为止所拥有的

use std::fs::File;
use std::io::Read;
use std::str::Chars;

pub struct Lexer<'a> {
    file_name: String,
    file_contents: String,
    iterator: Option<Chars<'a>>,
}

impl<'a> Lexer<'a> {

    fn new(fname: &str) -> Lexer {
        Lexer {
            file_name: fname.to_string(),
            file_contents: String::new(),
            iterator: None,
        }
    }


    // Reads the file contents and creates iterator
    fn init(&'a mut self) { 

        // Open the file
        let mut f = File::open(&self.file_name).expect("Couldn't open file");

        // Read the contents
        f.read_to_string(&mut self.file_contents).expect("Couldn't read file contents");

        self.iterator = Some(self.file_contents.chars());

    }

    // Gets the next character
    fn get_next(&mut self) -> Option<char> {

        self.iterator.unwrap().next()

    }

}

fn main() {

    let mut lexer = Lexer::new("test.txt");
    lexer.init();

    // Assuming the file "text.txt" contains "Hello World" 
    // then the following two lines should print "H" then "e"

    println!("{}", lexer.get_next().unwrap());
    println!("{}", lexer.get_next().unwrap());

}

第一个错误的Google显示,
Clone()
-ing是此类错误的可能解决方案,但我相信这在这种情况下不起作用,因为迭代器状态需要在每次调用
next()
时更新


有人对如何克服这些问题并将其编译出来有什么建议吗?

最终,您正在尝试。与其他公式不同,这种特殊情况允许您“打结”引用,但可能无法满足您的需要。例如,在调用
init
之后,您将永远无法移动
Lexer
,因为移动它将使引用无效

它还解释了“再次借用”错误。因为生命周期应用于自我,并且它是一个可变的引用,所以lexer本身将永远保留可变的引用,这意味着任何其他东西都无法对其进行变异,包括它自己

简单的回答是:不要这样组织代码。无论出于何种原因,解析和词法分析都是Rust社区中的一个普遍问题。看看其他库是如何做到这一点的

或者看看迭代器一般是如何工作的。被迭代的项保持不变,并返回一个引用原始项的单独迭代器


将代码分成相同的两部分可能是最好的方向。

好吧,我得到了一半。我现在让水壶开着煮咖啡。下次我会在回答之前喝咖啡,哈。
cannot move out of borrowed content [E0507]
main.rs:38          self.iterator.unwrap().next()
cannot borrow `lexer` as mutable more than once at a time [E0499]
main.rs:49      println!("{}", lexer.get_next().unwrap());