英文:
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...
英文:
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...
答案1
得分: 4
不确定文档中有什么不清楚。
如果所有字段都是 Clone,可以在 #[derive] 中使用此特质。由 Clone 派生的实现会调用每个字段的 clone 方法。
对于通用结构体,#[derive] 通过在通用参数上添加 Clone 约束来有条件地实现 Clone。
从关于 Send
的文档中,你可以看到 Arc<T>
如果其内容是 Sync + Send
,则是 Send
。
是否更好地单独包装每个字段或整个结构体在 Arc
中取决于你的用例,但通常每个 Arc
都会带来一些开销,所以越少越好。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论