gpt4 book ai didi

rust - 解构一个可变的可窥视迭代器

转载 作者:行者123 更新时间:2023-11-29 08:18:32 25 4
gpt4 key购买 nike

我正在尝试遍历 &[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>

最佳答案

您可能应该回去刷新一下自己 mutability with the book . Peekable::peek返回一个不可变引用:

impl<I> Peekable<I>
where
I: Iterator,
{
fn peek(&mut self) -> Option<&<I as Iterator>::Item>
// ^^^^^^^^^^^^^^^^^^^^^^
}

因为它是不可变的,你...不能改变它。

&mut b'-' => {
if let Some(next) = iter.peek() {
if b'-' == **next {
*ch = b' ';
mode = Mode::COMMENT;
}
}
}

关于rust - 解构一个可变的可窥视迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48081244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com