I'm writing a simple tokenizer in Rust but I'm having trouble. I've simplified the code a bit for the sake of this question:
use std::iter::Peekable;
use std::str::Chars;
struct Example<'a> {
it: Peekable<Chars<'a>>,
}
impl<'a> Example<'a> {
fn tokenize_string(&mut self) {
loop {
match self.it.peek() {
None => break,
Some(_x) => self.it.next(),
};
}
}
}
The error I'm getting is:
error[E0499]: cannot borrow `self.it` as mutable more than once at a time
--> src/main.rs:13:29
|
11 | match self.it.peek() {
| ------- first mutable borrow occurs here
12 | None => break,
13 | Some(_x) => self.it.next(),
| ^^^^^^^ second mutable borrow occurs here
14 | };
| - first borrow ends here
I've been able to work around this by creating a copy of the iterator and calling peek()
on that:
fn tokenize_string(&mut self) {
loop {
let mut iterator = self.it.clone();
match iterator.peek() {
None => break,
Some(_x) => self.it.next(),
};
}
}
Is this the best way to do this? It seems a little hack-ish.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…