-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombiningSmartPointer.rs
More file actions
58 lines (39 loc) · 945 Bytes
/
CombiningSmartPointer.rs
File metadata and controls
58 lines (39 loc) · 945 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::cell::RefCell;
use std::rc::Rc;
struct Person
{
tasks: u8
}
impl Person
{
fn work(&mut self,name :&str)
{
println!("{0:?} is working",name);
self.tasks -= 1;
}
}
struct Worker
{
name:String,
person:Rc<RefCell<Person>>
}
//Rc(refernce counter) smart pointer for collective ownership
//RefCell is a datastructure of smart pointer which gives us the mutable access to imuutable data
impl Worker
{
fn task(&self)
{
let mut person = self.person.borrow_mut();
person.work(&self.name);
}
}
fn main()
{
let person = Rc::new(RefCell::new(Person{tasks:4}));
let hr= Worker {name:String::from("Ram"),person:person.clone()};
let manager= Worker {name:String::from("Shyam"),person:person.clone()} ;
manager.task();
hr.task();
let borrow_person = person.borrow();
println!("Remaining task : {0:?}",borrow_person.tasks);
}