如何从向量的不同部分获取两个可变借项?

时间:2019-06-26 13:01:05

标签: rust borrow-checker

比方说,我想使用位纠缠的骇客交换向量的第一项和第三项:

fn main() {
    let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7];

    {
        let first_item = &mut v[0];
        let third_item = &mut v[2];
        *first_item ^= *third_item;
        *third_item ^= *first_item;
        *first_item ^= *third_item;
    }

    println!("{:?}", v);
}

铁锈不喜欢这样:

   Compiling mcve v0.0.0 (/home/wizzwizz4/rust/mcve)
error[E0499]: cannot borrow `v` as mutable more than once at a time
 --> src/main.rs:6:31
  |
5 |         let first_item = &mut v[0];
  |                               - first mutable borrow occurs here
6 |         let third_item = &mut v[2];
  |                               ^ second mutable borrow occurs here
7 |         *first_item ^= *third_item;
  |         -------------------------- first borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0499`.
error: Could not compile `mcve`.

To learn more, run the command again with --verbose.

那很好,因为我只想更改v[0]

fn main() {
    let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7];

    {
        let first_item = &mut v[0];
        *first_item = v[2];
    }

    println!("{:?}", v);
}

我又被卡住了

   Compiling mcve v0.0.1 (/home/wizzwizz4/rust/mcve)
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
 --> src/main.rs:6:23
  |
5 |         let first_item = &mut v[0];
  |                               - mutable borrow occurs here
6 |         *first_item = v[2];
  |         --------------^---
  |         |             |
  |         |             immutable borrow occurs here
  |         mutable borrow later used here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0502`.
error: Could not compile `mcve`.

To learn more, run the command again with --verbose.

问题是, I 知道这两个借用都来自向量的不同部分。具体来说,我知道第一个索引是<= 1,第二个索引是> 1

我该如何告诉Rust编译器呢?

0 个答案:

没有答案