Skip to content

Clone documentation can be confusing to beginners around "duplication" language #141138

@Eveheeero

Description

@Eveheeero

Hi, I'm mainly using rust for developing application

I wonder is it safe to impl Clone for Arc<Mutex>

Arc is a frequently used pattern for modifying data in multiple places.

However, if you end up cloning a parent struct that contains an Arc, it's hard to tell that the data inside is the same data without knowing more about the internal structure

For example

#[derive(Clone)]
struct Context {
  things: Object,
  id_to_object: Arc<Mutex<usize, BigObject>>,
}
impl ThreadContext {
  fn add_data(id: usize, obj: BigObject) -> ...;
}
// I cloned ctx to reuse it, but when I call `add_data`, we see that the original ctx also modified
let ctx = old_ctx.clone();

This becomes more likely to happen whenever you wrap it in a parent that implements #[derive(Clone)].

So I thought that struct with Arc<Mutex> shouldn't be able to implement clone as simply as writing #[derive(Clone)].

Is this unsafe? or is it something that users should be aware of?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions