Skip to content

Instantly share code, notes, and snippets.

@hbjydev
Last active March 28, 2025 18:34
Show Gist options
  • Save hbjydev/3db3079a09dd0582926dc704263dd366 to your computer and use it in GitHub Desktop.
Save hbjydev/3db3079a09dd0582926dc704263dd366 to your computer and use it in GitHub Desktop.
// Type you want to build
struct MyThing {}
trait MyBuilder {
type OutputType;
fn build(&self) -> OutputType;
}
struct MyThingBuilder {}
impl MyBuilder for MyThingBuilder {
type OutputType = MyThing;
fn build(&self) -> String { /* ... */ } // Won't compile, returns the wrong type
fn build(&self) -> MyThing { /* ... */ } // Will compile, returns the right type
}
@hbjydev
Copy link
Author

hbjydev commented Mar 28, 2025

This pattern allows the trait to be generic without specifying a MyBuilder<T>-style thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment