☰ All patterns
Prototype
Make new objects by cloning an existing one, deeply.
01
Explain it like I'm new
Real-life analogy
Photocopying a form
Instead of designing a new invoice from scratch, you photocopy a blank template and fill it in. Scribbling on your copy must never change the original.
😩 The problem
Copying a struct in Go (b := *a) copies slice and map headers, NOT their contents. Edit the copy's slice and you silently corrupt the original.
💡 The pattern
Give the type a Clone() method that makes a deep copy, with fresh slices and maps, so the clone is fully independent.
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…
- •Creating many similar objects from a pre-configured template.
- •Handing data to other goroutines or callers who might mutate it.
🚫 Skip it when…
- •The struct only holds plain values (ints, strings). A normal copy is already deep.
🐹 Go tip
Since Go 1.21, slices.Clone and maps.Clone make deep-ish copies trivial. Nested pointers still need manual cloning.
🌍 You've already seen it in
http.Request.Clone(ctx), tls.Config.Clone() and http.Header.Clone().
04
Quick check
One question. No pressure.
After `b := *a`, which field is still SHARED between a and b?