0

I have the following function:

fn merge_results_from(counters: Vec<JoinHandle<HashMap<char, usize>>>) -> HashMap<char, usize> {
    let mut total_count_by_character = HashMap::<char, usize>::new();
    for counter in counters {
        let count_by_character = counter.join()
                .unwrap();
        for (key, val) in count_by_character.iter() {
            *total_count_by_character.entry(*key).or_default() += val;
        }
    }
    total_count_by_character
}

This works as expected, but I prefer a more functional style of coding, so I refactored it to:

    counters.iter()
            .map(|counter| counter.join().unwrap())
            .fold(HashMap::new(), |mut accumulator, count_by_character| {
                for (key, val) in count_by_character.iter() {
                    *accumulator.entry(*key).or_default() += val;
                }
                accumulator
            })

Which fails with

error[E0507]: cannot move out of *counter which is behind a shared reference --> src\lib.rs:65:28 | 65 | .map(|counter| counter.join().unwrap()) | ^^^^^^^ move occurs because *counter has type JoinHandle<HashMap<char, usize>>, which does not implement the Copy trait

How can I make this work?

Brian Kessler
  • 1,896
  • 5
  • 24
  • 39

0 Answers0