From: Martin Pitt Date: Sun, 29 Aug 2021 14:12:41 +0000 (+0200) Subject: concepts: Rewrite Post without Option X-Git-Url: https://piware.de/gitweb/?a=commitdiff_plain;h=c2e012ab539dff44f0690e5d7cab4880400454fe;p=learn-rust.git concepts: Rewrite Post without Option This gets rid of a lot of extra Option handling code, at the price of having to rebuild instead of pass through non-changing states. --- diff --git a/concepts/src/lib.rs b/concepts/src/lib.rs index ca06241..bb15eeb 100644 --- a/concepts/src/lib.rs +++ b/concepts/src/lib.rs @@ -110,14 +110,14 @@ impl Iterator for Counter5 { } pub struct Post { - state: Option>, + state: Box, content: String, } impl Post { pub fn new() -> Post { Post { - state: Some(Box::new(Draft {})), + state: Box::new(Draft {}), content: String::new(), } } @@ -127,27 +127,21 @@ impl Post { } pub fn content(&self) -> &str { - // as_ref() converts Option> to Option<&Box> - // state can never be None, all state transitions return a new one - self.state.as_ref().unwrap().content(self) + self.state.content(self) } pub fn request_review(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.request_review()); - } + self.state = self.state.request_review(); } pub fn approve(&mut self) { - if let Some(s) = self.state.take() { - self.state = Some(s.approve()); - } + self.state = self.state.approve(); } } trait State { - fn request_review(self: Box::) -> Box; - fn approve(self: Box::) -> Box; + fn request_review(&self) -> Box; + fn approve(&self) -> Box; #[allow(unused_variables)] fn content<'a>(&self, post: &'a Post) -> &'a str { @@ -157,33 +151,34 @@ trait State { struct Draft {} impl State for Draft { - fn request_review(self: Box::) -> Box { + fn request_review(&self) -> Box { Box::new(PendingReview {}) } - fn approve(self: Box::) -> Box { - self + fn approve(&self) -> Box { + // don't change state + Box::new(Self {}) } } struct PendingReview {} impl State for PendingReview { - fn request_review(self: Box::) -> Box { - self + fn request_review(&self) -> Box { + Box::new(Self {}) } - fn approve(self: Box::) -> Box { + fn approve(&self) -> Box { Box::new(Published {}) } } struct Published {} impl State for Published { - fn request_review(self: Box::) -> Box { - self + fn request_review(&self) -> Box { + Box::new(Self {}) } - fn approve(self: Box::) -> Box { + fn approve(&self) -> Box { Box::new(Published {}) }