Shallow Copy and Move in rust

3k views Asked by At

Is is possible for rust to have shallow copies, because it would appear that a move replaces a shallow copy?

1

There are 1 answers

5
hellow On BEST ANSWER

You have to differentiate based on the underlying type.

You can't do a shallow copy of struct Foo(String); because two instances of Foo would point at the very same String, which would violate the strict aliasing rule .

However, if you are having a reference counter, e.g. struct Foo(Rc<String>); it is possible, because Rc will prevent you from doing unsafe things, e.g. having a mutable reference, when there are others references on the String.

It is also possible for types that implement [Clone] to make a "shallow" copy, because Copy implies, that the type can be copied by using memcpy (e.g. a u32 or a &T).

What is the difference between Copy and Clone? is also very worth reading.


So, in general no: Exceptions are reference counted structs (Rc or Arc) , Cloneables, or references (&T), because they don't violate the strict aliasing rule.