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
+25-1Lines changed: 25 additions & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -28,6 +28,30 @@ Primitive types like integers or floats already have a native syntax for constru
28
28
29
29
-**Placement** : In C++, the constructor also determines where in memory the object is initialized.
30
30
31
+
32
+
## Move Semantic: Copy and Clone
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:
35
+
-`Clone`: [Create a deep, independent copy of the value](<https://doc.rust.org/std/clone/trait.Clone.html>).
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`.
39
+
40
+
41
+
`Copy` constructor are done implicitly, and are fast..
42
+
43
+
```rs
44
+
letvalue=42;
45
+
letvalue2=value; // implicit copy
46
+
```
47
+
48
+
...and `Clone` constructor are done explicitly, and are slower because the object is generaly heavier to duplicate.
49
+
50
+
```rs
51
+
letvalue="hello".to_owned(); // 1 memory allocation, can't be bit copied
0 commit comments