By independent copy, I'm going to assume you mean "no (mutable) shared state possible".
Rust does not support independent copies . You can't assume you can ever get an independent copy in generic context.
(There may be some exceptions with heavy gymnastics, but they're not something you'll see in day-to-day programming and won't really be what you're talking about here.)
Getting an independent copy is not the contract of Clone
.
The entire point of having an Rc
is shared ownership. Not getting a deep clone is not dangerous, it's the point of the data type.
The recommendation is because you can't prevent trait methods that take &self
from being called on the implementing type method-call style, so Rc
can't do what it normally does and have fn clone(this: &Self)
here to emphasize you're not calling clone
on the enclosed object.
I personally use rc.clone()
unless there's something more confusing going on that requires type annotations to make clear. If you don't know what cloning an Rc
does, I think you have larger problems.
If by correct/safe cloning, you mean "guaranteed to generate independent copies", that's what the "magical deep clone" you dismissed explored. Maybe you could get something less complicated if you limited the types severely enough -- you seem fine not implementing it for RefCell
for example. However if by "must not be misused", you want an actual guarantee, then it still must be an unsafe
trait.
One could explore the idea of a good-faith trait (not unsafe
so no guarantee). But needing a deep clone in the context of an Rc
is an exception, not the rule.
If the developer doesn't understand Rc
, they're going to misinterpret a lot of things, sure. There's presumably a reason Rc
is being used and if they don't understand it and especially if they start to try to circumvent it, a lot of things could go wrong. They should learn about Rc
and why it's being used.
Maybe it's just being used for performance... but if there's interior mutability within, it's probably being used because shared state is desired. In that case, the developer is going to have to learn about interior mutability.
The "independent copy" misconception is not an Rc
specific thing though:
fn foo<T: Mutable>(mut thing: T) {
// I received ownership so no one can observe my changes right?
thing.mutate();
}
fn bar(mimut: &MyInteriorMutabilityUsingType) {
// Wrong.
foo(mimut);
}
In a generic context, you can't prevent the possibility of someone handing you a type containing, or indirectly using, interior mutability.
Rust doesn't support giving you a way to prevent that.