当我克隆一个包含 Arc 的结构体时会发生什么?

huangapple go评论61阅读模式
英文:

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&lt;String&gt;
}

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&lt;String&gt;,
}

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&lt;T&gt; 如果其内容是 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&lt;T&gt; 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.

huangapple
  • 本文由 发表于 2023年2月24日 03:10:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定