I am using Rust for a project. I met a weird bug in my code that I couldn’t figure out.
- I have a fairly complicated struct, say
struct Foo, and let it derive
Foohas the ownership of some of its fields such as
MyEnum::Var(Bar), but shares some fields by
Arc<T>(which does not quite matter in this case).
- Some fields is locked with RwLock/Mutex, so that I have to implement
Clonetrait. I acquire the lock, and clone its inner data, and wrap it in a new lock.
Baralso owns some of its fields (say
Baz) through the same way. This chain goes on for several layers, and all the structs (
Baz, etc) have
Clonetrait, and owned by
When I create
Foo, I immediately
clone the struct as a copy and hope to keep it as original data. I only make mutations on one copy, and leave the other copy unchanged. However, I end up finding that
Baz is changed in both copies. In my understanding, derived
Clone trait on
Vec does deep copying, and if
Foo actually owns (does not share) its fields, cloning
Foo will also cloning its fields (and the fields of its fields). I have no idea why it ends up as both copies get modified. I would appreciate any input.
Thanks a lot.