You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/posts/constructor_in_rust/index.md
+28-5Lines changed: 28 additions & 5 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -31,27 +31,50 @@ Primitive types like integers or floats already have a native syntax for constru
31
31
32
32
## Move Semantic: Copy and Clone
33
33
34
-
In Rust, there are two traits that can be automatically implemented for a type: `Clone` and `Copy`. I don't want to enter to much details about the difference between the two, but here are the main differences:
34
+
In Rust, there are 2 traits for duplicating a value: `Clone` and `Copy`.
35
35
-`Clone`: [Create a deep, independent copy of the value](<https://doc.rust.org/std/clone/trait.Clone.html>).
36
36
37
-
-`Copy`: [Types whose values can be duplicated simply by copying bits.](<https://doc.rust.org/std/marker/trait.Copy.html>) is a marker trait that imply `Clone`.
38
-
Type that have have a field that have an indirection layer in memory such as `Box`, `Vec`, `String`, `HashMap`, `HashSet`, etc can't be `Copy`, just `Clone`.
37
+
-`Copy`: [Types whose values can be duplicated simply by copying bits.](<https://doc.rust.org/std/marker/trait.Copy.html>) is a marker trait that implies `Clone`.
38
+
By *marker* trait, I mean there is no logic in the `Copy` trait itself the definiton is: `pub trait Copy: Clone { }`. The compiler ensure that the type implements `Clone` and that it can be bit copied. All the logic for duplicating a value is in the `Clone` trait.
39
+
40
+
Type that have have a field that have an indirection layer in memory such as `Box`, `Vec`, `String`, `HashMap`, `HashSet`, etc can't be `Copy`, just `Clone`.
39
41
40
42
41
43
`Copy` constructor are done implicitly, and are fast..
42
44
43
45
```rs
44
46
letvalue=42;
45
-
letvalue2=value; // implicit copy
47
+
letvalue2=value; // implicit copy because it is cheap to do.
46
48
```
47
49
48
50
...and `Clone` constructor are done explicitly, and are slower because the object is generaly heavier to duplicate.
49
51
50
52
```rs
51
-
letvalue="hello".to_owned(); // 1 memory allocation, can't be bit copied
53
+
letvalue="hello".to_owned(); // 1 memory allocation, and can't be bit copied
0 commit comments