Created
October 27, 2025 01:19
-
-
Save robert-king/f546f8639c22f4bd84030fa446bad80f to your computer and use it in GitHub Desktop.
builder 2 (no unwrap() needed)
This file contains hidden or 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
| struct Unset; | |
| struct PizzaBuilder<Dough, Topping> { | |
| dough: Dough, | |
| topping: Topping, | |
| } | |
| impl<T> PizzaBuilder<Unset, T> { | |
| fn with_dough(self, dough: &str) -> PizzaBuilder<String, T> { | |
| PizzaBuilder { | |
| dough: dough.to_string(), | |
| topping: self.topping, | |
| } | |
| } | |
| } | |
| impl<T> PizzaBuilder<T, Unset> { | |
| fn with_topping(self, topping: &str) -> PizzaBuilder<T, String> { | |
| PizzaBuilder { | |
| topping: topping.to_string(), | |
| dough: self.dough, | |
| } | |
| } | |
| } | |
| impl PizzaBuilder<String, String> { | |
| fn build(self) -> Pizza { | |
| Pizza { | |
| dough: self.dough, | |
| topping: self.topping, | |
| } | |
| } | |
| } | |
| #[derive(Debug)] | |
| struct Pizza { | |
| #[allow(dead_code)] | |
| dough: String, | |
| #[allow(dead_code)] | |
| topping: String, | |
| } | |
| impl Pizza { | |
| fn builder() -> PizzaBuilder<Unset, Unset> { | |
| PizzaBuilder { | |
| dough: Unset, | |
| topping: Unset, | |
| } | |
| } | |
| } | |
| fn main() { | |
| let x = Pizza::builder() | |
| .with_topping("topping") | |
| .with_dough("dough") | |
| .build(); | |
| print!("{x:?}"); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment