A high-performance deep cloning library for Go state that safe reflection can
observe, with exact Cloner[T] support for type-owned private state.
DeepClone is intentionally honest: it clones supported in-memory values, preserves supported object relationships, and returns an error for runtime or resource state that cannot be meaningfully deep-cloned.
For the durable clone contract and forbidden semantics, see SPECS/01-clone-contract.md.
- Generic API: Clone Go values with
deepclone.Clone(value). - Honest errors: Unsupported state returns
UnsupportedErrorwith path, type, and reason. - Fast common paths: Primitives, scalar slices, and scalar maps avoid reflection overhead.
- Graph safety: Pointer cycles, map cycles, slice cycles, and shared pointer targets are preserved.
- Custom cloning: Implement
Cloner[T]for equivalent reconstruction of private state and invariants. - Concurrent use: Package state is safe under concurrent cloning.
- No runtime dependencies: Core library uses only the Go standard library.
go get github.com/kaptinlin/deepcloneRequires Go 1.26.5 or later.
package main
import (
"fmt"
"github.com/kaptinlin/deepclone"
)
func main() {
original := map[string][]int{
"numbers": {1, 2, 3},
"scores": {85, 90, 95},
}
cloned, err := deepclone.Clone(original)
if err != nil {
panic(err)
}
original["numbers"][0] = 999
fmt.Println(original["numbers"])
fmt.Println(cloned["numbers"])
}Output:
[999 2 3]
[1 2 3]
func Clone[T any](src T) (T, error)
func MustClone[T any](src T) T
type Cloner[T any] interface {
Clone() (T, error)
}
type UnsupportedError struct {
Path string
Type reflect.Type
Reason string
}Use Clone in production paths where unsupported state should be handled. Use MustClone for tests, fixtures, and values that are already known to be supported.
type User struct {
Name string
Friends []string
Config map[string]any
}
user := User{
Name: "Alice",
Friends: []string{"Bob", "Charlie"},
Config: map[string]any{"theme": "dark"},
}
cloned, err := deepclone.Clone(user)
if err != nil {
return err
}
cloned.Friends[0] = "Eve"user.Friends remains unchanged because supported slices, maps, arrays, structs, pointers, and interfaces are cloned recursively.
type Worker struct {
Ch chan int
}
_, err := deepclone.Clone(map[string]Worker{
"main": {Ch: make(chan int)},
})
if err != nil {
var unsupported *deepclone.UnsupportedError
if errors.As(err, &unsupported) {
fmt.Println(unsupported.Path) // $[*].Ch
fmt.Println(unsupported.Reason) // channels cannot be cloned
}
}Unsupported paths describe structural locations and intentionally omit map key contents. A single unsupported occurrence has a stable path, type, and reason. When an unordered map contains several unsupported occurrences, which one is reported first is unspecified.
type Document struct {
Title string
Content []byte
Version int
}
func (d Document) Clone() (Document, error) {
content, err := deepclone.Clone(d.Content)
if err != nil {
return Document{}, err
}
return Document{
Title: d.Title,
Content: content,
Version: d.Version,
}, nil
}Types that implement Cloner[T] own the equivalent reconstruction of their
private state. The returned value must keep the same logical meaning while its
mutable state remains independent. Circular reference detection does not apply
inside custom Clone methods.
DeepClone preserves supported object relationships:
- pointer cycles
- map cycles
- slice cycles
- shared pointer targets
- shared non-empty slice values with the same length and capacity
- pointer-to-struct-field relationships when the addressable owner is cloned in the same graph
- pointer-to-array-element relationships when the addressable owner is cloned in the same graph
Addressable owner relationships are preserved even when an interior pointer is encountered before its owner during traversal.
Slice nilness and length are preserved. Slice capacity is an allocation detail and is not part of the public contract.
DeepClone does not promise full backing-array alias reconstruction for distinct subslices, and it does not promise map entry interior pointer reconstruction.
| Value kind | Clone behavior |
|---|---|
| Nil pointers, slices, maps, interfaces, channels, functions, unsafe pointers | Preserved as nil |
| Non-nil channels | Return UnsupportedError |
| Non-nil functions | Return UnsupportedError |
| Non-nil unsafe pointers | Return UnsupportedError |
| Sync primitives and atomic state | Return UnsupportedError |
| File handles | Return UnsupportedError |
| Unexported value-like struct fields | Preserved by shallow struct copy |
| Unexported direct or nested reference-like struct fields | Return UnsupportedError; implement Cloner[T] for private invariants |
| Named external types with private mutable state | Return UnsupportedError at the public type boundary; wrap with an exact Cloner[T] when the type needs equivalent reconstruction |
DeepClone keeps common operations fast with primitive, scalar slice, and scalar map fast paths plus cached reflection metadata for structs.
task benchRun comparison benchmarks against other clone libraries:
task bench-comparisonWhen publishing benchmark numbers, record the date, CPU, OS, Go version, command, and raw output source. Comparison numbers are meaningful only after the specific clone semantics being compared are checked by the comparison module's conformance tests.
task deps # Download and tidy dependencies
task lint # Run golangci-lint and tidy checks
task test # Run tests with -race
task verify # Run the full local verification pipelineFor development rules, see AGENTS.md.
See examples/ for runnable examples covering basic values, circular references, and custom clone behavior.
This project is licensed under the MIT License - see the LICENSE file for details.