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
python
from flask import Blueprint, jsonify, request, abort v1 = Blueprint("users_v1", __name__) v2 = Blueprint("users_v2", __name__)
Versioning a Flask API with Blueprints
api versioning
blueprints
rest
Intermediate
7 steps
go
package theme import ( "fmt"
Per-tenant HTML templates with Gin's renderer
multi-tenancy
concurrency
html-templates
Advanced
8 steps
go
package auth import ( "net/http"
Setting and reading secure session cookies in Go
cookies
session-management
security
Intermediate
6 steps
go
package middleware import ( "net/http"
A maintenance-mode gate in Gin
middleware
atomic-flag
concurrency
Intermediate
8 steps
go
func ServeVideo(c *gin.Context) { id := c.Param("id") video, err := videoRepo.FindByID(c.Request.Context(), id) if err != nil {
Streaming video files with Gin
http streaming
range requests
file serving
Intermediate
6 steps
go
package handler type LineItem struct { SKU string `json:"sku" binding:"required,alphanum"`
Structured validation errors in Gin
validation
json-binding
error-handling
Intermediate
8 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.