1

I have this code:

use std::collections::HashMap;

#[derive(Copy, Clone, PartialEq, Hash, Debug)]
struct Coord(i32, i32);
#[derive(Copy, Clone, PartialEq, Debug)]
enum State {
    OFF,
    ON,
    MID,
}
type NewMapType = HashMap<Coord, State>;

fn do_map_operation(some_map: &NewMapType) -> i32 {
    let mut answer = 0;

    for (key, value) in some_map.into_iter() {
        let new_point = call_another_function(&some_map);
        // This is an error - the compiler complains that this `some_map`
        // does not implement the Copy trait but whereas
        // both the key and the value implement the Copy trait.
        answer += new_point;
    }

    answer
}

fn main() {
    let mut newMap: NewMapType = HashMap::new();
    newMap.insert(Coord(0, 0), STATE::OFF);
    let some_answer = do_map_operation(&newMap);
    println!("{}", some_answer);
}

How should I be implementing the Copy trait for a HashMap so that I can safely use copies of the map across multiple functions?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Wave Metric
  • 129
  • 1
  • 3
  • 13
  • TL;DR the duplicate: you don't / can't. Implement `Clone` instead. You may also be interested in [How do I share a mutable object between threads using Arc?](https://stackoverflow.com/q/31373255/155423) or [How can I pass a reference to a stack variable to a thread?](https://stackoverflow.com/q/32750829/155423). – Shepmaster Jan 05 '21 at 20:29
  • By the way, idiomatic Rust uses `snake_case` for variables, methods, macros, fields and modules; `UpperCamelCase` for types and enum variants; and `SCREAMING_SNAKE_CASE` for statics and constants. – Shepmaster Jan 05 '21 at 20:30
  • 1
    It's hard to answer your question because it doesn't include a [MRE]. We can't tell what crates (and their versions), types, traits, fields, etc. are present in the code. It would make it easier for us to help you if you try to reproduce your error on the [Rust Playground](https://play.rust-lang.org) if possible, otherwise in a brand new Cargo project, then [edit] your question to include the additional info. There are [Rust-specific MRE tips](//stackoverflow.com/tags/rust/info) you can use to reduce your original code for posting here. Thanks! – Shepmaster Jan 05 '21 at 20:30

0 Answers0