Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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...

like image 351
onx2 Avatar asked Oct 24 '25 16:10

onx2


1 Answers

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.

like image 123
cafce25 Avatar answered Oct 27 '25 09:10

cafce25