Skip to content
เข้าสู่ระบบ

Typestate Pattern

Pattern สำหรับ compile-time state machine validation

// States as empty structs
struct Draft;
struct Review;
struct Published;
// Document with state type parameter
struct Document<State> {
content: String,
_state: std::marker::PhantomData<State>,
}
impl Document<Draft> {
fn new(content: &str) -> Self {
Document {
content: content.to_string(),
_state: std::marker::PhantomData,
}
}
fn edit(&mut self, new_content: &str) {
self.content = new_content.to_string();
}
// Transition to Review
fn submit_for_review(self) -> Document<Review> {
println!("Submitting for review...");
Document {
content: self.content,
_state: std::marker::PhantomData,
}
}
}
impl Document<Review> {
// Can only publish from Review state
fn approve(self) -> Document<Published> {
println!("Approved!");
Document {
content: self.content,
_state: std::marker::PhantomData,
}
}
fn reject(self) -> Document<Draft> {
println!("Rejected, back to draft");
Document {
content: self.content,
_state: std::marker::PhantomData,
}
}
}
impl Document<Published> {
fn get_content(&self) -> &str {
&self.content
}
}
fn main() {
let mut doc = Document::<Draft>::new("Initial content");
doc.edit("Better content");
let doc = doc.submit_for_review();
// doc.edit("x"); // Error! Not in Draft state
let doc = doc.approve();
println!("Published: {}", doc.get_content());
}

เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม

ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด