1
1
# Clone
2
2
3
3
When dealing with resources, the default behavior is to transfer them during
4
- assignments or function calls. However, sometimes we need to make a
4
+ assignments or function calls. However, sometimes we need to make a
5
5
copy of the resource as well.
6
6
7
- The [ ` Clone ` ] [ clone ] trait helps us do exactly this. Most commonly, we can
7
+ The [ ` Clone ` ] [ clone ] trait helps us do exactly this. Most commonly, we can
8
8
use the ` .clone() ` method defined by the ` Clone ` trait.
9
9
10
10
``` rust,editable
11
11
// A unit struct without resources
12
12
#[derive(Debug, Clone, Copy)]
13
- struct Nil ;
13
+ struct Unit ;
14
14
15
15
// A tuple struct with resources that implements the `Clone` trait
16
16
#[derive(Clone, Debug)]
17
17
struct Pair(Box<i32>, Box<i32>);
18
18
19
19
fn main() {
20
- // Instantiate `Nil `
21
- let nil = Nil ;
22
- // Copy `Nil `, there are no resources to move
23
- let copied_nil = nil ;
20
+ // Instantiate `Unit `
21
+ let unit = Unit ;
22
+ // Copy `Unit `, there are no resources to move
23
+ let copied_unit = unit ;
24
24
25
- // Both `Nil `s can be used independently
26
- println!("original: {:?}", nil );
27
- println!("copy: {:?}", copied_nil );
25
+ // Both `Unit `s can be used independently
26
+ println!("original: {:?}", unit );
27
+ println!("copy: {:?}", copied_unit );
28
28
29
29
// Instantiate `Pair`
30
30
let pair = Pair(Box::new(1), Box::new(2));
@@ -37,7 +37,7 @@ fn main() {
37
37
// Error! `pair` has lost its resources
38
38
//println!("original: {:?}", pair);
39
39
// TODO ^ Try uncommenting this line
40
-
40
+
41
41
// Clone `moved_pair` into `cloned_pair` (resources are included)
42
42
let cloned_pair = moved_pair.clone();
43
43
// Drop the original pair using std::mem::drop
@@ -52,4 +52,4 @@ fn main() {
52
52
}
53
53
```
54
54
55
- [ clone ] : https://doc.rust-lang.org/std/clone/trait.Clone.html
55
+ [ clone ] : https://doc.rust-lang.org/std/clone/trait.Clone.html
0 commit comments