From: Martin Pitt Date: Sun, 29 Aug 2021 14:21:01 +0000 (+0200) Subject: concepts: Add Post.reject() transition X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=6cf2fd87f634bb24ca0ab801a8ba3fbfff1ac418;p=learn-rust.git concepts: Add Post.reject() transition --- diff --git a/concepts/src/lib.rs b/concepts/src/lib.rs index bb15eeb..923b80b 100644 --- a/concepts/src/lib.rs +++ b/concepts/src/lib.rs @@ -137,11 +137,16 @@ impl Post { pub fn approve(&mut self) { self.state = self.state.approve(); } + + pub fn reject(&mut self) { + self.state = self.state.reject(); + } } trait State { fn request_review(&self) -> Box; fn approve(&self) -> Box; + fn reject(&self) -> Box; #[allow(unused_variables)] fn content<'a>(&self, post: &'a Post) -> &'a str { @@ -159,6 +164,10 @@ impl State for Draft { // don't change state Box::new(Self {}) } + + fn reject(&self) -> Box { + Box::new(Self {}) + } } struct PendingReview {} @@ -170,6 +179,10 @@ impl State for PendingReview { fn approve(&self) -> Box { Box::new(Published {}) } + + fn reject(&self) -> Box { + Box::new(Draft {}) + } } struct Published {} @@ -182,6 +195,10 @@ impl State for Published { Box::new(Published {}) } + fn reject(&self) -> Box { + Box::new(Self {}) + } + fn content<'a>(&self, post: &'a Post) -> &'a str { &post.content } diff --git a/concepts/src/main.rs b/concepts/src/main.rs index f9eafe9..3e9bbbd 100644 --- a/concepts/src/main.rs +++ b/concepts/src/main.rs @@ -256,6 +256,12 @@ fn test_dyn_traits() { post.request_review(); assert_eq!("", post.content()); + post.reject(); + assert_eq!("", post.content()); + + post.request_review(); + assert_eq!("", post.content()); + post.approve(); assert_eq!(text, post.content()); }