Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

You can't really have State pattern w/o inheritance. At very least it becomes very awkward.


This page of Rust's Book shows how to implement exactly the State pattern without inheritance, and it feels pretty natural. Rust's traits do have inheritance but that isn't used here - at first there is one trait, State, but by the time we're writing idiomatic Rust there are no traits at all.

https://doc.rust-lang.org/book/ch17-03-oo-design-patterns.ht...

We end up with three types of post, Post, DraftPost and PendingReviewPost, and our state pattern is implemented by the type transitions implemented in these three types. When you call Post::new() you get a DraftPost, and the only way to get a Post from that is to request the review, obtaining a PendingReviewPost and have somebody accept it to get the Post from there.




Consider applying for YC's Winter 2026 batch! Applications are open till Nov 10

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: