Using `Arc<Mutex<T>>>`. Compiler tells me I am using a moved value

Hello Everyone,

I am trying to build a Web socket server and trying to develop a broadcaster.
Basically the thread is supposed to wait for new connection and mutate the Vector to add those new connection into the Vector.
I am using a Arc<Mutex> to contain all the socket, like this :

impl Broadcaster {
    pub fn new(addr: &'static str) -> Broadcaster {
        let map = Arc::new(Mutex::new(Vec::new()));
        thread::Builder::new()
            .name("WebSocketManager".to_string())
            .spawn(move || handle_broadcast(addr, Arc::clone(&map)))
            .expect("Could not start the server");
        Broadcaster { connection_list: map }
    }
}

and the error is :

error[E0382]: use of moved value: `map`
   --> src/socket_manager.rs:166:40
    |
161 |         let map = Arc::new(Mutex::new(Vec::new()));
    |             --- move occurs because `map` has type `Arc<std::sync::Mutex<Vec<WebSocketStream<tokio::net::TcpStream>>>>`, which does not implement the `Copy` trait
...
164 |             .spawn(move || handle_broadcast(addr, Arc::clone(&map)))
    |                    ------- value moved into closure here      --- variable moved due to use in closure
165 |             .expect("Could not start the server");
166 |         Broadcaster { connection_list: map }
    |                                        ^^^ value used here after move

Do you have any ideas of what could be the problem ?
Sorry if that is something trivial, I'm quite new in the community

Thanks :slight_smile:

Clone the Arc before you capture it in the closure.

Thank you a lot

I have been so much into it, I haven't seen it :cry:

No worries. Welcome to the community, by the way!

1 Like

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.