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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Encoding then decoding through gob yields a deep copy where nested pointers, slices, and maps are fully independent.
- 2Go generics let one Clone function work for any type without reflection boilerplate or per-type code.
- 3The serialize-round-trip trick is simple but pays a marshalling cost and only copies gob-encodable exported fields.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
go
package middleware import ( "net/http"
Per-plan export limits in Gin middleware
middleware
rate-limiting
authorization
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/deep-copying-any-value-with-gob-in-go-explained-go-f8f9/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.