diff --git a/state_pattern_types/Cargo.toml b/state_pattern_types/Cargo.toml new file mode 100644 index 0000000..c66b710 --- /dev/null +++ b/state_pattern_types/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "state_pattern_types" +version = "0.1.0" +authors = ["laurens "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/state_pattern_types/src/main.rs b/state_pattern_types/src/main.rs new file mode 100644 index 0000000..14ed679 --- /dev/null +++ b/state_pattern_types/src/main.rs @@ -0,0 +1,55 @@ +pub struct DraftPost { + content: String, +} + +pub struct PendingReviewPost { + content: String, +} + +pub struct Post { + content: String, +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +fn main() { + let mut post = Post::new(); + + post.add_text("I ate a salad for lunch today"); + + let post = post.request_review(); + + let post = post.approve(); + + assert_eq!("I ate a salad for lunch today", post.content()); +}