我使用函数时出错了,因为借用一个可变的,如果也有一个不可变的借用,就不允许像多次借用可变的一样。
pub fn _function(list: &mut Vec<char>) {
for (n, c) in list.iter().enumerate() {
if *c == ' ' {
list.remove(n);
}
}
}error[E0502]: cannot borrow `*list` as mutable because it is also borrowed as immutable
--> src/lib.rs:4:14
|
2 | for (n, c) in list.iter().enumerate() {
| -----------------------
| |
| immutable borrow occurs here
| immutable borrow later used here
3 | if *c == ' ' {
4 | list.remove(n);
| ^^^^^^^^^^^^^^ mutable borrow occurs here我遇到的唯一解决办法就是克隆列表。
pub fn _function(list: &mut Vec<char>) {
for (n, c) in list.clone().iter().enumerate() {
if *c == ' ' {
list.remove(n);
}
}
}我想知道是否还有其他解决方案来使用这两个函数而不用克隆列表和使用更多的内存。
发布于 2021-06-16 13:59:49
没有一种通用的同时读取和修改vec的方法。但对于具体案件,有一些临时的解决办法。
在这里,您可以使用retain来修改vec,只保留验证谓词的元素:
pub fn _function(list: &mut Vec<char>) {
list.retain(|&c| c != ' ');
}https://stackoverflow.com/questions/68004041
复制相似问题