Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

rust - How can I solve "use of moved value" and "which does not implement the `Copy` trait"?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...