From 5fa2d10adb1203f2695ea0ce8531e92707840a90 Mon Sep 17 00:00:00 2001 From: Julio Biason Date: Wed, 27 Feb 2019 18:39:58 -0300 Subject: [PATCH] Use defaults, so the structre can extend without changing too much code --- src/main.rs | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1f271e9..1b442b3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,29 +8,31 @@ enum CurrentTag { Title } +#[derive(Default)] struct State { tag: Option, - title: String + title: Option } impl State { pub fn new() -> Self { - Self { tag: None, title: String::from("") } + Self { tag: None, title: None } } pub fn change_title(self, title:&str) -> Self { - Self { tag:self.tag, - title:title.to_string() } + Self { title: Some(title.to_string()), + ..Default::default() + } } pub fn change_tag(self, tag:CurrentTag) -> Self { - Self { tag:Some(tag), - title:self.title } + Self { tag: Some(tag), + ..Default::default() } } pub fn remove_tag(self) -> Self { - Self { tag:None, - title:self.title } + Self { tag: None, + ..Default::default() } } } @@ -60,6 +62,7 @@ fn main() { Event::ElementStart(tag) => { match tag.name.as_ref() { "title" => state.change_tag(CurrentTag::Title), + "note" => State::new(), // the start of a note resets everything _ => state } }, @@ -71,7 +74,8 @@ fn main() { match state.tag { Some(CurrentTag::Title) => { println!("TITLE: {}", slugify(&data)); - state.change_title(&slugify(data)) + let new_state = state.change_title(&slugify(&data)); + new_state }, _ => state }