Skip to content

Instantly share code, notes, and snippets.

@utkarshg6
Created May 16, 2022 04:03
Show Gist options
  • Save utkarshg6/507560be53345b20aca8304f477fa0b0 to your computer and use it in GitHub Desktop.
Save utkarshg6/507560be53345b20aca8304f477fa0b0 to your computer and use it in GitHub Desktop.
This is an implementation of State Pattern in Rust, which doesn't follow state pattern.
pub struct Post {
content: String,
}
pub struct DraftPost {
content: String,
}
pub struct PendingReviewPost {
content: String,
}
impl Post {
pub fn new() -> DraftPost {
DraftPost {
content: String::new(),
}
}
pub fn content(&self) -> &str {
&self.content
}
}
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
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_state_pattern_works() {
let mut post = Post::new();
post.add_text("I ate a salad for lunch today");
// We're storing it in a new variable instead of just only calling it.
let post = post.request_review();
let post = post.approve();
assert_eq!("I ate a salad for lunch today", post.content());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment