Execute a function without cloning its parameter

the function run converts a map into a queue. Threads get the items from this queue and consume it.
Is it possible to execute the function run without cloning the map in the function(let map=map.clone();)?

const MAX_THREADS:u8=8;

fn run(map:&HashMap<String, f64>)
    let q = Arc::new(ArrayQueue::new(map.len()));
    let map=map.clone();
    let mut handles=Vec::with_capacity(map.len());
    for item in map
        q.push(item).expect("pushing failed");

    for _ in 0..MAX_THREADS
        let q=Arc::clone(&q);
        let handle = thread::spawn(move || {
            let q = Arc::clone(&q);
                let item = q.pop();
                if item == None

                //do something with the item
                println!("{} {}", item.as_ref().unwrap().0, item.as_ref().unwrap().1);
    for handle in handles

fn main() {

    let mut map=HashMap::new();
    for i in 0..100
            format!("Foo_{}", i),
            i as f64


Why don't you just take it by value, then?

1 Like

There are a lot more things wrong with your code, by the way. In no particular order of importance:

  • the formatting is very non-idiomatic. Run rustfmt on your code, and read the style guide.
  • Your way of looping over the queue is unnecessarily roundabout, and you are cloning the queue Arc unnecessarily.
  • Instead of declaring collections as mutable and then inserting in a trivial loop, you can use iterator chains with collect() to avoid mutability in the simple cases.
  • You should handle errors instead of just unwrap()ing everything.

All in all, here is the improved code.


Thank for the improved code. I am a beginner in Rust. I have to learn a lot:(

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.