如何解决“使用已移动的值”和“未实现`Copy`特性”的问题?

13

我正在尝试从向量中读取值,并将这些值用作索引执行加法操作:

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个回答

12
这个问题的解决方法是借用正在迭代的Vec,而不是移动它:
for element_index in &additions {
    let addition_aux = values[*element_index];
    addition = addition_aux + addition;
}

但是你的代码还有其他问题。你从未通过添加或删除元素来更改additions,因此你的while additions.len() > 0永远不会终止。我希望这是因为你还没有完成,并想先解决即时问题再编写函数的其余部分。
暂时来说,您可能会受益于重新阅读Rust Book中关于所有权、移动和借用的章节

谢谢,是的,我有一个我用Perl编写的简单程序。我正在逐步翻译它,发现了这个问题。我知道它会进入无限循环,因为停止条件还没有出现。 - fontar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接