Working with &mut

I'm working with ws-rs, and have the below upon open socket:

impl Handler for Client {

    fn on_open(&mut self, _: Handshake) -> Result<()> {
        println!("sockect: {:#?}", self.out);
        Ok(())
    }
}

Trying to manipulate self, as:

pub struct Socket{
    socket: Sender,
    unique_id: String
}

fn on_open(&mut self, _: Handshake) -> Result<()> {
        let socket= Socket{ socket: self.out, unique_id: "".to_string() };
}

But got this error:

error[E0507]: cannot move out of `self.out` which is behind a mutable reference
  --> src/socket.rs:35:37
   |
35 |         let socket= Socket{ socket: self.out, unique_id: "".to_string() };
   |                                     ^^^^^^^^ move occurs because `self.out` has type `ws::communication::Sender`, which does not implement the `Copy` trait

It looks I'm not clear about borrowing with &mut :frowning:

Well, your Socket needs an owned Sender. But your method is working on &mut self, a borrowed reference, and you can't just remove its Sender and leave nothing in its place.

What you can do, depending on what the actual behavior is meant to be:

  • in Self, use Option<Sender> and take it out using Option::take()
  • replace the Sender by a dummy one using std::mem::replace()
  • clone the Sender to get a second, owned one (if the type allows you to)
1 Like

Did not get it, what shall I do!

It looks like Sender implements Clone. Just clone it:

pub struct Socket{
    socket: Sender,
    unique_id: String
}

fn on_open(&mut self, _: Handshake) -> Result<()> {
        let socket= Socket{ socket: self.out.clone(), unique_id: "".to_string() };
}
1 Like

Thanks a lot

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.