Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What happens when I clone a struct with Arc inside?

I would like to know what happens when I clone a struct that has properties inside of Arc.

#[derive(Clone)]
pub struct Foo {
  bar: Arc<String>
}

When I call clone on Foo, what happens? Is it safe to share the Foo struct between threads and use the underlying Arc or should I do something like this?

#[derive(Clone)]
pub struct Foo
where
    Foo: Sync + Send,
{
    bar: Arc<String>,
}

I’m essentially just trying to nest a bunch of structs into one so I can more easily share them with different things. Would it make more sense to have the wrapper struct as an Arc and unwrap the properties? I can provide more context if necessary but wanted to keep it abstract for now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve used a non-grouped up version of all my Arcs directly in the places I needed them which is also fine but cumbersome. I’m not really sure how to test this…

>Solution :

Not sure what’s unclear in the documentation.

This trait can be used with #[derive] if all fields are Clone. The derived implementation of Clone calls clone on each field.

For a generic struct, #[derive] implements Clone conditionally by adding bound Clone on generic parameters.

From the docs on Send you can see Arc<T> is Send if its content is Sync + Send

If you better wrap each field separately or the whole struct in an Arc depends on your usecase but usually every Arc comes with overhead so the fewer the better.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading