go 36 lines · 6 steps

Deep copying any value with gob in Go

A generic Clone function serializes a value through gob and decodes it back to produce a fully independent copy.

Explained by highlit
1package deepcopy
2 
3import (
4 "bytes"
5 "encoding/gob"
6)
7 
8type Address struct {
9 Street string
10 City string
11 Zip string
12}
13 
14type Profile struct {
15 Name string
16 Emails []string
17 Address *Address
18 Metadata map[string]string
19}
20 
21func Clone[T any](src T) (T, error) {
22 var dst T
23 
24 var buf bytes.Buffer
25 enc := gob.NewEncoder(&buf)
26 if err := enc.Encode(src); err != nil {
27 return dst, err
28 }
29 
30 dec := gob.NewDecoder(&buf)
31 if err := dec.Decode(&dst); err != nil {
32 return dst, err
33 }
34 
35 return dst, nil
36}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Encoding then decoding through gob yields a deep copy where nested pointers, slices, and maps are fully independent.
  2. 2Go generics let one Clone function work for any type without reflection boilerplate or per-type code.
  3. 3The serialize-round-trip trick is simple but pays a marshalling cost and only copies gob-encodable exported fields.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Deep copying any value with gob in Go — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code