A fundamental guide
Fundamental Traits
This note wants to guide you to understand these traits and other useful methods that you might encounter frequently. There are many fundamental and useful traits in Rust. It is important to understand then and, in the future, this can help you to understand what others’ code are writing about.
Traits
Clone && Copy
Probably, the first time learning Rust, these two are the first two that you will encounter. They have more things to talk about but we currently focus on more basic stuffs.
Clone
Reference - There are two methods in this trait
fn clone(&self) -> Self;
fn clone_from(&mut self, source: &Self) { ... }
As mentioned in the documentation, Clone
is always explicit and may or may not be expensive. Remember that, Clone
is more general
than Copy
.
Additionally, Clone
cannot be applied on the dyn trait directly because dyn requires the objects to be object-safe! The workaround here is adding the extra object safe object to contain the struct. It can be Box, Rc, or else. Here is the example. There is a crate called dyn-clone which will be your useful tool as well.
Copy
Reference - Mentioned in Clone section, Copy is more restrictive form. Copy
is just a Marker trait
that derives Clone
. The difference here is that, Copy only handles T
that can be bit-wise copied and it happens implicitly.
A Good Explanation - The implementation of Clone can provide any type-specific behavior necessary to duplicate values safely. For example, the implementation of Clone for String needs to copy the pointed-to string buffer in the heap. A simple bitwise copy of String values would merely copy the pointer, leading to a double free down the line. For this reason, String is Clone but not Copy. Note: Copy and Drop are mutually exclusive. Therefore, when a type dervies Drop, it cannot drive Copy reference. More precisely, Copy means “it is safe to bitwise-copy the value and keep using the original value. Last but not least, every move is bitwise-copy, so this is impportant for you to think about designing your code.
Debug && Display
Display is similar to Debug but Debug
is for debugging usage. Besides, when a type derive Display
, it automatically implement ToString. When a type implements fmt::Display
, it can faithfully be represented as UTF-8 reference. Lastly, Display
is recommned to be implemented compared with ToString
.
To Be Continued