我正在尝试迭代&[u8]
的可变缓冲区,只要有--
删除所有字节,直到遇到'\n'
我尝试了这种方法,它给出了一个我无法解决的错误
fn remove_comments_in_place<'a>(buffer: &'a mut [u8]) {
#[derive(PartialEq)]
enum Mode {
COMMENT,
CODE,
}
let mut mode = Mode::CODE;
let mut iter = buffer.iter_mut().peekable();
while let Some(ch) = iter.next() {
match ch {
// Look 2 chars ahead to identify comments
&mut b'-' => {
if let Some(&&mut ref mut hyphen) = iter.peek() {
if hyphen == &mut b'-' {
*hyphen = b' ';
*ch = b' ';
mode = Mode::COMMENT;
}
}
}
&mut b'\r' => *ch = b' ',
&mut b'\n' => {
*ch = b' ';
if mode == Mode::COMMENT {
mode = Mode::CODE;
}
}
_ => if mode == Mode::COMMENT {
*ch = b' '
},
}
}
}
我得到的错误是:
error[E0389]: cannot borrow data mutably in a `&` reference
--> src/main.rs:13:35
|
13 | if let Some(&&mut ref mut hyphen) = iter.peek() {
| ^^^^^^^^^^^^^^ assignment into an immutable reference
我也尝试将作业更改为
&mut b'-' => {
if let Some(&&mut hyphen) = iter.peek() {
if hyphen == b'-' {
hyphen = b' ';
*ch = b' ';
mode = Mode::COMMENT;
}
}
}
但收到以下错误:
warning: value assigned to `hyphen` is never read
--> src/main.rs:15:25
|
15 | hyphen = b' ';
| ^^^^^^
|
= note: #[warn(unused_assignments)] on by default
error[E0384]: re-assignment of immutable variable `hyphen`
--> src/main.rs:15:25
|
13 | if let Some(&&mut hyphen) = iter.peek() {
| ------ first assignment to `hyphen`
14 | if hyphen == b'-' {
15 | hyphen = b' ';
| ^^^^^^^^^^^^^ re-assignment of immutable variable
This question suggests my destructuring is correct,那么我如何使用hyphen
分配到Option<&mut T>
?
答案 0 :(得分:1)
你可能应该回过头来自我介绍mutability with the book。 Peekable::peek
返回不可变引用:
library(dplyr)
library(tidyr)
inputTest %>%
tbl_df %>%
gather(date, value, matches("^\\d+") )
因为它是不可变的你......不能改变它。
impl<I> Peekable<I>
where
I: Iterator,
{
fn peek(&mut self) -> Option<&<I as Iterator>::Item>
// ^^^^^^^^^^^^^^^^^^^^^^
}