-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtraits.rs
78 lines (61 loc) · 1.44 KB
/
traits.rs
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#![allow(dead_code)]
struct SeaCreature
{
pub name:String,
noise:String
}
impl SeaCreature
{
pub fn get_sound(&self) -> &str
{
return &self.noise;
}
}
trait NoiseMaker //interface and aggregrate
{
fn make_noise(&self);
fn make_alot_of_noise(&self)
{
self.make_noise();
self.make_noise();
}
}
impl NoiseMaker for SeaCreature
{
fn make_noise(&self)
{
println!("{0:?}",&self.get_sound());
}
fn make_alot_of_noise(&self)
{
for _ in 0..3
{
self.make_noise();
}
}
}
//dispatching is an oop paradigm where we call a method on an object and the compiler decides which method to call based on the type of the object.
// static and dyanmic dispatch where dynamic dispactch dosent know the instances we are using so we use traits objects.
//use of dyn keyword.
fn static_make_noise(creature: &SeaCreature)
{
creature.make_noise();
}
fn dynamic_make_noise(noise_maker : &dyn NoiseMaker)
{
noise_maker.make_alot_of_noise();
}
fn main()
{
let creature = SeaCreature{
name:String::from("ferris"),
noise:String::from("bulb")
};
println!("making small noise :");
creature.make_noise();
println!("make more noise :");
creature.make_alot_of_noise();
println!("*************");
static_make_noise(&creature);
dynamic_make_noise(&creature);
}