I want to iterate over every character in a String using the char_indices()
method and while iterating through it removing specific characters.
(This is just a simplified example of what I am really doing)
But I get error E0502 (which I fully understand why).
How can I solve this?
Code
fn main() {
let mut string = String::from("some 42 test string");
for (idx, character) in string.char_indices() {
if character.is_numeric() {
// Do something
string.remove(idx);
}
}
}
Error
4 | for (idx, character) in string.char_indices() {
| ---------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
...
7 | string.remove(idx);
| ^^^^^^^^^^^^^^^^^^ mutable borrow occurs here