rust - Rust 借用奇怪的行为
问题描述
就像下面的 rust 代码:while
循环编译并运行良好,但for iter
版本没有编译,由于错误:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:22:9
|
20 | for i in v.iter() {
| --------
| |
| immutable borrow occurs here
| immutable borrow later used here
21 | println!("v[i]: {}", i);
22 | v.push(20);
| ^^^^^^^^^^ mutable borrow occurs here
error: aborting due to previous error
但是据了解,while
loop也有同样的场景,len
也是不可变借用,为什么和as借用可变get
不冲突呢?push
请指教我在这里缺少什么理解,非常感谢您的启发!
fn main() {
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
v.push(4);
let mut i = 0;
while i < v.len() && i < 10 {
v.push(20);
println!("v[i]: {:?}", v.get(i));
i += 1;
}
// for i in v.iter() {
// println!("v[i]: {}", i);
// v.push(20);
// }
}
解决方案
您的for
代码版本大致相当于以下内容:
fn main() {
let mut v = Vec::new();
v.push(1);
v.push(2);
v.push(3);
v.push(4);
let mut it = v.iter();
while let Some(i) = it.next() {
println!("v[i]: {}", i);
v.push(20);
}
}
如果你尝试编译它,你会得到一个可能更有意义的错误:
error[E0502]: cannot borrow `v` as mutable because it is also borrowed as immutable
--> src/main.rs:11:9
|
8 | let mut it = v.iter();
| - immutable borrow occurs here
9 | while let Some(i) = it.next() {
| -- immutable borrow later used here
10 | println!("v[i]: {}", i);
11 | v.push(20);
| ^^^^^^^^^^ mutable borrow occurs here
迭代器v
在循环的整个持续时间内不可变地借用,因此您不能在循环内进行任何可变借用。
当然,即使你能做到这一点,你最终也会陷入无限循环,因为你不断地追加另一个项目。
推荐阅读
- appium-ios - 如何使用 selenium java appium 在手机中进行长滑动或滑动并按住?
- python - 获取单词中字符的数值,并与编码的数字进行算术运算
- ajax - 如果在 laravel 中验证失败,则返回错误
- spring-boot - 轮询弹簧启动执行器端点的更好方法(流式传输而不是轮询?)
- xml - 使用scrapy,如何从标签内部获取价值
- subdomain - 添加自定义域
- c - 这个 C 程序根据学生排名对学生数组大小进行排序 5。那些排名需要通过选择和插入排序方法进行排序
- flutter - 如何在指定索引中添加值?
- javascript - javascript值gettng在函数中丢失
- python - 删除重复数据并将其余数据附加到 pandas