Created
July 19, 2018 17:11
-
-
Save Niakr1s/f90767d99d0b72ed435dabbb49af1ff2 to your computer and use it in GitHub Desktop.
RustBook 2nd edition 17.3 (2nd part implementation)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
pub enum Content { | |
Post(String), | |
DraftPost(String), | |
PendingReviewPost(String), | |
} | |
pub struct Post { | |
approved: i32, | |
content: Content, | |
} | |
impl Post { | |
pub fn new() -> Post { | |
Post { | |
approved: 0, | |
content: Content::DraftPost(String::new()) | |
} | |
} | |
pub fn content<'a>(&'a self) -> &'a str { | |
match self.content { | |
Content::Post(ref e) => e, | |
_ => "", | |
} | |
} | |
pub fn add_text(mut self, text: &str) -> Post{ | |
match self.content { | |
Content::DraftPost(ref mut e) => { | |
e.push_str(text); | |
}, | |
_ => (), | |
}; | |
self | |
} | |
pub fn request_review(self) -> Post { | |
match self.content { | |
Content::DraftPost(e) => Post { approved: 0, content: Content::PendingReviewPost(e) }, | |
_ => self, | |
} | |
} | |
pub fn approve(mut self) -> Post { | |
self.increase_approve(); | |
match self.content { | |
Content::PendingReviewPost(ref e) if self.approved >= 2 => { | |
Post { approved: 0, content: Content::Post(e.to_string())} | |
}, | |
_ => self, | |
} | |
} | |
fn increase_approve(&mut self) { | |
match self.content { | |
Content::PendingReviewPost(_) => self.approved += 1, | |
_ => (), | |
} | |
} | |
pub fn to_draft(self) -> Post { | |
match self.content { | |
Content::Post(e) => Post { | |
approved: 0, | |
content: Content::DraftPost(e), | |
..self | |
}, | |
_ => self, | |
} | |
} | |
pub fn reject(self) -> Post { | |
match self.content { | |
Content::PendingReviewPost(e) => Post { approved: 0, content: Content::DraftPost(e)}, | |
_ => self, | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate rust_learn; | |
use rust_learn::Post; | |
fn main() { | |
let post = Post::new() | |
.add_text("I ate a salad for lunch today") | |
.request_review() | |
.approve() | |
.approve() | |
.to_draft() | |
.add_text("\nLalalala") | |
.request_review() | |
.approve() | |
.reject() | |
.request_review() | |
.approve() | |
.approve(); | |
assert_eq!("I ate a salad for lunch today\nLalalala", post.content()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment