首页 > 解决方案 > 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

但是据了解,whileloop也有同样的场景,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);
        
    // }
    
}

标签: rustborrow

解决方案


您的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在循环的整个持续时间内不可变地借用,因此您不能在循环内进行任何可变借用。

当然,即使你能做到这一点,你最终也会陷入无限循环,因为你不断地追加另一个项目。


推荐阅读