Why do all methods in a chain of calls except the last need a mutable reference to a mutable iterator?
My intention is to change the internal state of the iterator (...: &mut std::slice::Iter<u8>
), not the pointer/reference itself (mut it: ...
). My intuition is built on this answer.
fn main() {
let v = vec![1, 2, 3];
let mut it = v.iter();
match it.next() {
Some(v) => {
fun1(&mut it);
println!("{:?}", v);
}
None => (),
}
}
fn fun1(mut it: &mut std::slice::Iter<u8>) {
// ^-- why mut?
match it.next() {
Some(v) => {
fun2(&mut it);
println!("{:?}", v);
}
None => (),
}
}
fn fun2(it: &mut std::slice::Iter<u8>) {
// ^-- not needed
match it.next() {
Some(v) => {
println!("{:?}", v);
}
None => (),
}
}
When I remove this mut
, I get this error:
error[E0596]: cannot borrow `it` as mutable, as it is not declared as mutable
--> src/main.rs:18:18
|
14 | fn fun1(it: &mut std::slice::Iter<u8>) {
| -- help: consider changing this to be mutable: `mut it`
...
18 | fun2(&mut it);
| ^^^^^^^ cannot borrow as mutable