@@ -20,6 +20,7 @@ impl Post {
20
20
}
21
21
22
22
pub fn request_review ( & mut self ) {
23
+ //self.state = Some(self.state.take().expect("Valid state").request_review());
23
24
if let Some ( s) = self . state . take ( ) {
24
25
self . state = Some ( s. request_review ( ) )
25
26
}
@@ -29,11 +30,31 @@ impl Post {
29
30
self . state = Some ( s. approve ( ) )
30
31
}
31
32
}
33
+
34
+ pub fn reject ( & mut self ) {
35
+ if let Some ( s) = self . state . take ( ) {
36
+ self . state = Some ( s. reject ( ) )
37
+ }
38
+ }
32
39
}
33
40
41
+
42
+ /*
43
+ Note the capitalized "self" in Box<Self>.
44
+
45
+ self is a keyword used within methods to represent the instance of the struct or enum on which the method is called.
46
+ - It is similar to this in other languages.
47
+ - It is a reference to the instance of the struct or enum on which the method is invoked.
48
+
49
+ Self is a special type in Rust that represents the type of the implementing struct or enum itself.
50
+ - It is often used in trait definitions to refer to the type that is implementing the trait.
51
+ - It is useful when you want to write generic code using traits and refer to the implementing type within the trait definition.
52
+ */
53
+
34
54
trait State {
35
55
fn request_review ( self : Box < Self > ) -> Box < dyn State > ;
36
56
fn approve ( self : Box < Self > ) -> Box < dyn State > ;
57
+ fn reject ( self : Box < Self > ) -> Box < dyn State > ;
37
58
fn content < ' a > ( & self , _post : & ' a Post ) -> & ' a str {
38
59
""
39
60
}
@@ -49,6 +70,10 @@ impl State for Draft {
49
70
fn approve ( self : Box < Self > ) -> Box < dyn State > {
50
71
self
51
72
}
73
+
74
+ fn reject ( self : Box < Self > ) -> Box < dyn State > {
75
+ self
76
+ }
52
77
}
53
78
54
79
struct PendingReview { }
@@ -60,6 +85,11 @@ impl State for PendingReview {
60
85
fn approve ( self : Box < Self > ) -> Box < dyn State > {
61
86
Box :: new ( Published { } )
62
87
}
88
+ fn reject ( self : Box < Self > ) -> Box < dyn State > {
89
+ Box :: new ( Draft { } )
90
+
91
+ }
92
+
63
93
}
64
94
65
95
struct Published { }
@@ -75,4 +105,8 @@ impl State for Published {
75
105
fn content < ' a > ( & self , post : & ' a Post ) -> & ' a str {
76
106
& post. content
77
107
}
108
+
109
+ fn reject ( self : Box < Self > ) -> Box < dyn State > {
110
+ self
111
+ }
78
112
}
0 commit comments