Skip to content

Instantly share code, notes, and snippets.

@robert-king
Created October 27, 2025 01:19
Show Gist options
  • Save robert-king/f546f8639c22f4bd84030fa446bad80f to your computer and use it in GitHub Desktop.
Save robert-king/f546f8639c22f4bd84030fa446bad80f to your computer and use it in GitHub Desktop.
builder 2 (no unwrap() needed)
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