如何解决“使用移动值”和“不实现'复制'特征”?

时间:2018-03-15 21:52:45

标签: rust

我正在尝试从向量中读取值并使用值作为索引来执行添加:

fn main() {
    let objetive = 3126.59;

    // 27
    let values: Vec<f64> = vec![
        2817.42, 2162.17, 3756.57, 2817.42, -2817.42, 946.9, 2817.42, 964.42, 795.43, 3756.57,
        139.34, 903.58, -3756.57, 939.14, 828.04, 1120.04, 604.03, 3354.74, 2748.06, 1470.8,
        4695.71, 71.11, 2391.48, 331.29, 1214.69, 863.52, 7810.01,
    ];

    let values_number = values.len();
    let values_index_max = values_number - 1;

    let mut additions: Vec<usize> = vec![0];

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

    while additions.len() > 0 {
        let mut addition: f64 = 0.0;
        let mut saltar: i32 = 0;

        // Sumar valores en additions
        for element_index in additions {
            let addition_aux = values[element_index];
            addition = addition_aux + addition;
        }
    }
}

我收到以下错误。我该如何解决?

error[E0382]: use of moved value: `additions`
  --> src/main.rs:18:11
   |
18 |     while additions.len() > 0 {
   |           ^^^^^^^^^ value used here after move
...
23 |         for element_index in additions {
   |                              --------- value moved here
   |
   = note: move occurs because `additions` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `additions`
  --> src/main.rs:23:30
   |
23 |         for element_index in additions {
   |                              ^^^^^^^^^ value moved here in previous iteration of loop
   |
   = note: move occurs because `additions` has type `std::vec::Vec<usize>`, which does not implement the `Copy` trait

1 个答案:

答案 0 :(得分:4)

针对此特定问题的解决方法是借用您正在迭代的Vec而不是移动它:

for element_index in &additions {
    let addition_aux = values[*element_index];
    addition = addition_aux + addition;
}

但您的代码还有其他问题。您永远不会通过添加或删除元素来更改additions,因此您的while additions.len() > 0永远不会终止。我希望这是因为你还没有完成,并希望在编写函数的其余部分之前解决如何解决当前问题。

目前,您可能会从重新阅读the chapter of the Rust Book about ownership, moves, and borrowing中受益。