我有一个简单的解析器可以被提炼成这样的东西:
use std::str::Chars;
use std::iter::Peekable;
struct Parser<'a> {
input: Peekable<Chars<'a>>,
}
impl<'a> Parser<'a> {
fn new(input: &'a str) -> Self {
Parser {
input: input.chars().peekable(),
}
}
fn consume(&mut self, check: char) -> bool {
// see below
}
}
我consume
的原始实现,它应该看一下输入中的下一个字符并返回true(如果它与传递的字符匹配,则返回Peekable
),这是:
fn consume(&mut self, check: char) -> bool {
match self.input.peek() {
Some(c) if *c == check => {
self.input.next();
true
},
_ => false
}
}
编译告诉我,由于我已经在self.input
的调用中借用了next
,因此我无法通过peek
来调用error[E0499]: cannot borrow `self.input` as mutable more than once at a time
--> src/main.rs:18:17
|
16 | match self.input.peek() {
| ---------- first mutable borrow occurs here
17 | Some(c) if *c == check => {
18 | self.input.next();
| ^^^^^^^^^^ second mutable borrow occurs here
...
22 | }
| - first borrow ends here
。 / p>
&
我不明白为什么在Some
匹配表达式中添加*
(并从*c
删除fn consume(&mut self, check: char) -> bool {
match self.input.peek() {
Some(&c) if c == check => {
self.input.next();
true
},
_ => false
}
}
)会使代码编译:
c
基于Boiethios&#39;评论,如果Copy
不是cap_dropdown
,那么适当的解决方案是什么?