如何将可变数组划分为可变子数组

时间:2018-12-13 15:01:20

标签: arrays rust mutable

我需要将可变数组分为具有可变元素的3个可变子数组。

#[derive(Debug)]
struct Server {
    time: i64
}


impl Server {
    fn new(x: i64) -> Server {
        return Server {
            time: x
        }
    } 
}

fn main() {
      let mut arr = Vec::<Server>::new();
      arr.push(Server::new(10));
      arr.push(Server::new(20));
      arr.push(Server::new(30));
      arr.push(Server::new(40));
      arr.push(Server::new(50));

      let mut arr1 = arr.iter_mut().filter(|x| x.time > 20).collect::<Vec<&mut Server>>();
      let mut arr2 = arr.iter_mut().filter(|x| x.time < 20).collect::<Vec<&mut Server>>();
      let mut arr3 = arr.iter_mut().filter(|x| x.time == 20).collect::<Vec<&mut Server>>();
}

接下来,在每个子数组上执行不影响主数组的不同操作。 (例如,在不影响主数组顺序的情况下,首先对每个子数组进行排序。下一步是在每个子数组上操纵其元素。这些更改应反映在主数组的元素中。)

目前,在编译时除以Rust数组时,会出现以下错误:

error[E0499]: cannot borrow `arr` as mutable more than once at a time
  --> src/main.rs:26:18
   |
25 |   let mut arr1 = arr.iter_mut().filter(|x| x.time > 20).collect::<Vec<&mut Server>>();
   |                  --- first mutable borrow occurs here
26 |   let mut arr2 = arr.iter_mut().filter(|x| x.time < 20).collect::<Vec<&mut Server>>();
   |                  ^^^ second mutable borrow occurs here
 ...
29 | }
   | - first borrow ends here
error[E0499]: cannot borrow `arr` as mutable more than once at a time
  --> src/main.rs:27:18
   |
25 |   let mut arr1 = arr.iter_mut().filter(|x| x.time > 20).collect::<Vec<&mut Server>>();
   |                  --- first mutable borrow occurs here
26 |   let mut arr2 = arr.iter_mut().filter(|x| x.time < 20).collect::<Vec<&mut Server>>();
27 |   let mut arr3 = arr.iter_mut().filter(|x| x.time == 20).collect::<Vec<&mut Server>>();
   |                  ^^^ second mutable borrow occurs here
28 |   
29 | }
   | - first borrow ends here

1 个答案:

答案 0 :(得分:3)

您可以使用Iterator::partitionvec分成两个不同的vec,而无需克隆内部元素。 因为需要三个不同的分割,所以必须两次使用partition(顺序无关紧要)。

const THRESHOLD: i64 = 20;

let mut arr = Vec::<Server>::new();
arr.push(Server::new(10));
arr.push(Server::new(20));
arr.push(Server::new(30));
arr.push(Server::new(40));
arr.push(Server::new(50));

let (greater, rest): (Vec<_>, Vec<_>) = arr.into_iter().partition(|s| s.time > THRESHOLD);
let (equal, less): (Vec<_>, Vec<_>) = rest.into_iter().partition(|s| s.time == THRESHOLD);

playground

由于向量greaterequalless拥有相应的元素,因此您可以对其进行可变访问。