β° All patterns
Builder
Build a complicated object step by step, then validate once.
01
Explain it like I'm new
Real-life analogy
Building your own pizza
At the counter you say: large... thin crust... add mushrooms... add olives... extra cheese. Only when you say 'done' does the cook check it's valid and bake it.
π© The problem
A struct has lots of fields, some optional, some with rules ('at least one topping'). A constructor with 9 parameters is unreadable, and filling fields by hand skips validation.
π‘ The pattern
A builder type collects the settings through chained methods and remembers the first error. A final Build() validates everything and returns the finished value.
02
Walk through the code
Click a step to highlight its lines. This is a complete program you can copy and run.
Press βΆ Run to execute this program.This output was captured by running the program with Go 1.24. Copy it into your editor or the Go Playground and try changing things.
03
When should I use it?
β Reach for it whenβ¦
- β’Objects with many optional parts or multi-step assembly (queries, requests, documents).
- β’You want validation in one place instead of in every setter.
π« Skip it whenβ¦
- β’There are only 2β3 fields. Use a struct literal.
- β’Functional options would read better (very common in Go APIs).
πΉ Go tip
strings.Builder is the standard library's famous builder, used to build strings efficiently without lots of allocations.
π You've already seen it in
strings.Builder, SQL query builders like squirrel, and http.NewRequest followed by header setup.
04
Quick check
One question. No pressure.
Why does each builder method return the builder itself?
Related: Functional Options, Factory