Is structure without methods which take mutable reference sync and send?


#1

Let’s say I have a structure which only sends a request over the network. It has some fields but they can’t be changed since initialization because the structure’s implementation has no methods which take a mutable reference to the object but has one method which does it by move:

pub struct Client {
    client: reqwest::Client,
    keys: (String, String, String),
    oauth_token: Mutex<RefCell<AccessToken>>,
}
impl Client {
    fn (&self) -> Result<Object, Error>;
    // .... other methods like above
    fn (mut self) -> Self;
}

So, questions:

  1. Is this structure Send and Sync?
  2. Should I implement Send and Sync manually for them by using unsafe impl or they are derived automatically if the structure can be such?

#2

Whether the Sync and Send traits are derived for a struct does not depend on the existens of &mut self methods, it is purely determined by the members.

In general, do not implement them manually! There is a reason for types to not implement them, and ignoring that will lead to soundness bugs.

To check whether a struct is Send or Sync, use them accordingly or check it like this:

fn assert_sync<T: Sync>() {}
assert_sync::<Client>();

#3

There’s more information in the Rustonomicon.


#4

That’s kind of unusual. It’s typical to use either Mutex or RefCell for interior mutability, but I don’t think there’s any purpose in using both.


#5

Oh, yes, thanks much. I thought Mutex does not allow to change the object inside somewhy.