Closed
Description
Given the following code:
playground
fn main() {
let mut chars = "HHeelllloo,, wwoorrlldd!!".chars();
for c in chars.by_ref() {
print!("{}", c);
chars.next(); // Skip next
}
}
The current output is:
error[[E0499]](https://doc.rust-lang.org/stable/error-index.html#E0499): cannot borrow `chars` as mutable more than once at a time
--> src/main.rs:5:9
|
3 | for c in chars.by_ref() {
| --------------
| |
| first mutable borrow occurs here
| first borrow later used here
4 | print!("{}", c);
5 | chars.next(); // Skip next
| ^^^^^^^^^^^^ second mutable borrow occurs here
Ideally the output should look like:
error[[E0499]](https://doc.rust-lang.org/stable/error-index.html#E0499): cannot borrow `chars` as mutable more than once at a time
--> src/main.rs:5:9
|
3 | for c in chars.by_ref() {
| --------------
| |
| first mutable borrow occurs here
| first borrow later used here
4 | print!("{}", c);
5 | chars.next(); // Skip next
| ^^^^^^^^^^^^ second mutable borrow occurs here
note: a for loop advances the iterator for you. The result is stored in `c`.
help: if you want to call `next` within the loop, consider `while let`.
or similar. The note and/or help are both subject to changes, this is just a basic idea.
We could also conceivably rewrite the error message to expand on what the note says, like so:
error[[E0499]](https://doc.rust-lang.org/stable/error-index.html#E0499): cannot call `next` inside a for loop, as this results in two mutable borrows of `chars`.
--> src/main.rs:5:9
|
3 | for c in chars.by_ref() {
| --------------
| |
| first mutable borrow occurs here
| first borrow later used here
4 | print!("{}", c);
5 | chars.next(); // Skip next
| ^^^^^^^^^^^^ second mutable borrow occurs here
note: a for loop advances the iterator for you. The result is stored in `c`.
help: if you want to call `next` within the loop, consider `while let`.