Dealing with !Send type

I'm trying to implement a wrapper around web socket connection. One of the types, WebSocket type from web_sys, is !Send.

So I end up that my wrapper is also !Send, even if everything is inside Arc<Mutex<>>.

Current code for my wrapper is like this, this is not the actual code

struct Ws {
impl Ws {
  fn new() {
     let me = Self{...};
     spawn async {
        loop {
            // send data from outbox to actual websocket
            // read data from actual websocket into inbox
  fn send() { put into outbox }
  fn read() { pop from inbox }

So, it looks like I can solve the problem by not storing the web socket in the Ws struct, leaving it owned by the async closure. But I'm not too fond of this approach. Maybe it's just a habit from my previous experience with other languages, but I want to have a reference to it, at least I would be able to use it for debugging. What else can I do?

I imagine the problem with your struct being !Send comes from the fact that spawn requires the Future to be Send. Have you considered using spawn_local?

If that doesn't work, another common approach when dealing with !Send data is to manage it in just one thread and using channel to signal that thread to perform actions on it.

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.