Skip to content
GDP for Noobs
☰ All patterns
CreationalIntermediate

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.

main.go
1package main
2
3import (
4 "fmt"
5 "maps"
6 "slices"
7)
8
9type Document struct {
10 Title string
11 Tags []string // slices share memory when copied!
12 Meta map[string]string // maps share memory too!
13}
14
15// Clone makes a DEEP copy: new slice, new map, nothing shared.
16func (d *Document) Clone() *Document {
17 return &Document{
18 Title: d.Title,
19 Tags: slices.Clone(d.Tags),
20 Meta: maps.Clone(d.Meta),
21 }
22}
23
24func main() {
25 template := &Document{
26 Title: "Invoice Template",
27 Tags: []string{"finance", "draft"},
28 Meta: map[string]string{"author": "gopher"},
29 }
30
31 // The trap: a plain struct copy is SHALLOW.
32 shallow := *template
33 shallow.Tags[0] = "oops"
34 fmt.Println("template after shallow edit:", template.Tags)
35 template.Tags[0] = "finance" // undo the damage
36
37 // The fix: use Clone() for a deep copy.
38 inv := template.Clone()
39 inv.Title = "Invoice #42"
40 inv.Tags[1] = "sent"
41 inv.Meta["customer"] = "Acme"
42 fmt.Println("template:", template.Title, template.Tags, template.Meta)
43 fmt.Println("clone: ", inv.Title, inv.Tags, inv.Meta)
44}
terminal
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?

Related: Builder, Factory