How to do it...

  1. In the bin folder, create a file called shared.rs

  2. Add the following code and run it with cargo run --bin shared:

1    use std::rc::Rc;
2
3 // The ball will survive until all kids are done playing with
it
4 struct Kid {
5 ball: Rc<Ball>,
6 }
7 struct Ball;
8
9 fn main() {
10 {
11 // rc is created and count is at 1
12 let foo = Rc::new("foo");
13 // foo goes out of scope; count decreases
14 // count is zero; the object gets destroyed
15 }
16
17 {
18 // rc is created and count is at 1
19 let bar = Rc::new("bar");
20 // rc is cloned; count increases to 2
21 let second_bar = Rc::clone(&bar);
22 // bar goes out of scode; count decreases to 1
23 // bar goes out of scode; count decreases to 0
24 }
25
26 {
27 // rc is created and count is at 1
28 let baz = Rc::new("baz");
29 {
30 // rc is cloned; count increases to 2
31 let second_baz = Rc::clone(&baz);
32 // second_baz goes out of scode; count decreases to 1
33 }
34 // baz goes out of scode; count decreases to 0
35 }
36 let kid_one = spawn_kid_with_new_ball();
37 let kid_two = Kid {
38 ball: Rc::clone(&kid_one.ball),
39 };
40 let kid_three = Kid {
41 ball: Rc::clone(&kid_one.ball),
42 };
43 // ball lives until here
44 }
45
46 fn spawn_kid_with_new_ball() -> Kid {
47 let ball = Rc::new(Ball);
48 Kid {
49 ball: Rc::clone(&ball),
50 }
51 // Although the ball goes out of scope here, the object
behind it
52
53 // will survive as part of the kid
54 }
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.20.68