我如何解决“移动价值的使用"问题?和“哪个没有实现‘复制’特征"? [英] How can I solve "use of moved value" and "which does not implement the `Copy` trait"?

查看:26
本文介绍了我如何解决“移动价值的使用"问题?和“哪个没有实现‘复制’特征"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to read the values from a vector and use the values as indexes to perform an addition:

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;
        }
    }
}

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

I get the following error. How can I solve it?

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

推荐答案

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

The fix for this particular problem is to borrow the Vec you're iterating over instead of moving it:

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

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

but your code has other problems. You never change additions by adding or removing elements, so your while additions.len() > 0 will never terminate. I hope this is because you haven't finished and wanted to work out how to fix the immediate problem before writing the rest of the function.

现在,您可能会从重读 Rust Book 关于所有权、移动和借用的章节.

For now, you might benefit from re-reading the chapter of the Rust Book about ownership, moves, and borrowing.

这篇关于我如何解决“移动价值的使用"问题?和“哪个没有实现‘复制’特征"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆