4 ms·
> Even in Rust, the `Clone` trait produces a deep copy. Clone is not really a deep copy. I like the description that says it is "deep enough to give you an obj
by kzrdude 5y ago
> Even in Rust, the `Clone` trait produces a deep copy.
Clone is not really a deep copy. I like the description that says it is "deep enough to give you an object of identical/independent ownership (of what you started with), but no deeper".
Example: Rc<String> when cloned only gives you another handle to the Rc, the string data is not duplicated (for this reason we don't call it a real deep copy). You get a new rc handle that is on equal footing with the old handle.
There is plenty of Rust types that consist of tree-shaped ownership relations with no frills - in these cases clone and deep copy are identical. Let's say for example a HashMap<i32, String>.
- oconnor663 5y agoI think every "deep" copy ultimately has some limitation like this. Even in Python, an object can implement __deepcopy__() to prevent copy.deepcopy() from "copying too much", and things like file objects, classes, and modules get special treatment.
- kzrdude 5y agoI found that in Rust, you don't have to think about the distinction so much - not like you have to in for example Python and C# (pervasive/transparent object reference languages). In Rust it's predictable and mostly obvious which data is shared ownership or shared, and which is not. We don't need to talk about deep vs shallow copy semantics much in Rust. :)
- Blikkentrekker 5y agoYou are correct; my original definition that only went till `copy` was encountered is only the most common case of your more general definition. The principles are still quite similar and it still seems easier to implement to me than shallow copies as a generic trait. I don't know how I would fit shallow copies into Rust's trait system.
- kzrdude 5y agoClone seems to be the shallowest kind copy permitted by the type and ownership system.
- Blikkentrekker 5y agoWhich is why I find deep copies to be easier to implement than shallow. It is of course possible to express a shallower copy, but not in the same generic way as a universal trait, that I know of, in any case.