Use of moved value

I have a simple function in Rust that iterates through numbers and adds them to a vector if they fulfill a condition. This condition is a function that uses a previously defined variable, prime_factors.
The is_multiperfect function only needs to look things up in the prime_factors variable.

fn get_all_mpn_below(integer: usize) -> Vec<usize> {
    let prime_factors = get_prime_factors_below(integer);
    let mut mpn = vec![1];

    for n in (2..integer).step_by(2) {
        if is_multiperfect(n, prime_factors) {
            mpn.push(n);
        }
    }

    return mpn;
}

However, this yields the following error:

use of moved value: `prime_factors`

      let prime_factors = get_prime_factors_below(integer);
          ------------- move occurs because `prime_factors` has type `HashMap<usize, Vec<usize>>`, which does not implement the `Copy` trait

          if is_multiperfect(n, prime_factors) {
                                ^^^^^^^^^^^^^ value moved here, in previous iteration of loop

I’ve looked up the error and found it was about ownership, however I fail to understand how ownership applies here.
How can I fix this error?

>Solution :

as I don’t declare another variable.

Why would you think that’s relevant?

Moving is simply the default behaviour of Rust when transferring values (whether setting them, or passing them to function, or returning them from functions). This occurs for all types which are not Copy.

How can I fix this error?

Hard to say since the problem is is_multiperfect and you don’t provide that code, so the reader, not being psychic, has no way to know what is_multiperfect wants out of prime_factors.

Possible solutions are:

  • clone() the map, this creates a complete copy which the callee can use however it wants, leaving the original available, this gives the callee complete freedom but incurs a large cost for the caller
  • pass the map as an &mut (unique / mutable reference), if the callee needs to update it
  • pass the map as an & (shared reference), if the callee just needs to look things up in the map

Leave a Reply