Browse code

Use defaults, so the structre can extend without changing too much code

Julio Biason authored on 27/02/2019 13:39:58
Showing 1 changed files

... ...
@@ -8,29 +8,31 @@ enum CurrentTag {
8 8
     Title
9 9
 }
10 10
 
11
+#[derive(Default)]
11 12
 struct State {
12 13
     tag: Option<CurrentTag>,
13
-    title: String
14
+    title: Option<String>
14 15
 }
15 16
 
16 17
 impl State {
17 18
     pub fn new() -> Self {
18
-        Self { tag: None, title: String::from("") }
19
+        Self { tag: None, title: None }
19 20
     }
20 21
 
21 22
     pub fn change_title(self, title:&str) -> Self {
22
-        Self { tag:self.tag,
23
-               title:title.to_string() }
23
+        Self { title: Some(title.to_string()),
24
+               ..Default::default()
25
+         }
24 26
     }
25 27
 
26 28
     pub fn change_tag(self, tag:CurrentTag) -> Self {
27
-        Self { tag:Some(tag),
28
-               title:self.title }
29
+        Self { tag: Some(tag),
30
+               ..Default::default() }
29 31
     }
30 32
 
31 33
     pub fn remove_tag(self) -> Self {
32
-        Self { tag:None,
33
-               title:self.title }
34
+        Self { tag: None,
35
+               ..Default::default() }
34 36
     }
35 37
 }
36 38
 
... ...
@@ -60,6 +62,7 @@ fn main() {
60 62
             Event::ElementStart(tag) => {
61 63
                 match tag.name.as_ref() {
62 64
                     "title" => state.change_tag(CurrentTag::Title),
65
+                    "note" => State::new(),     // the start of a note resets everything
63 66
                     _ => state
64 67
                 }
65 68
             },
... ...
@@ -71,7 +74,8 @@ fn main() {
71 74
                 match state.tag {
72 75
                     Some(CurrentTag::Title) => {
73 76
                         println!("TITLE: {}", slugify(&data));
74
-                        state.change_title(&slugify(data))
77
+                        let new_state = state.change_title(&slugify(&data));
78
+                        new_state
75 79
                     },
76 80
                     _ => state
77 81
                 }