X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=blobdiff_plain;f=concepts%2Fsrc%2Flib.rs;h=bb15eeb814ea45d9aee64ed43497f586df33ba65;hp=ca0624142dea4d751e4506184bf84508de7e0696;hb=c2e012ab539dff44f0690e5d7cab4880400454fe;hpb=c182c6166ae3971320daaeadba3ea718124303e7 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 {}) }