deepclone

package module
v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2026 License: MIT Imports: 3 Imported by: 2

README ΒΆ

DeepClone

A high-performance deep cloning library for Go that provides safe, efficient copying of any Go value.

Go Version License Go Report Card

✨ Features

  • πŸš€ High Performance: Zero-allocation fast paths for primitive types
  • πŸ›‘οΈ Circular Reference Safe: Automatic detection and handling of circular references
  • πŸ”’ Thread Safe: Concurrent operations with safe caching mechanisms
  • πŸ“¦ Universal Support: Works with all Go types including channels, functions, and interfaces
  • 🎯 Extensible: Custom cloning behavior via Cloneable interface
  • ⚑ Zero Dependencies: Uses only Go standard library

πŸ“¦ Installation

go get github.com/kaptinlin/deepclone

πŸš€ Quick Start

package main

import (
    "fmt"
    "github.com/kaptinlin/deepclone"
)

func main() {
    // Deep clone any value
    original := map[string][]int{
        "numbers": {1, 2, 3},
        "scores":  {85, 90, 95},
    }
    
    cloned := deepclone.Clone(original)
    
    // Modify original - cloned remains independent
    original["numbers"][0] = 999
    
    fmt.Println("Original:", original["numbers"]) // [999, 2, 3]
    fmt.Println("Cloned:", cloned["numbers"])     // [1, 2, 3]
}

πŸ’‘ Core Concept

All operations perform deep copies by default:

  • Primitives: int, string, bool β†’ Copied by value (zero allocations)
  • Collections: slice, map, array β†’ New containers with cloned elements
  • Structs: New instances with all fields deeply cloned
  • Pointers: New pointers pointing to cloned values
  • Custom Types: Support via Cloneable interface

πŸ“š Examples

Basic Usage
// Primitives (zero allocation)
number := deepclone.Clone(42)
text := deepclone.Clone("hello")

// Collections (deep cloned)
slice := deepclone.Clone([]string{"a", "b", "c"})
data := deepclone.Clone(map[string]int{"key": 42})

// Complex structures
type User struct {
    Name    string
    Friends []string
    Config  map[string]interface{}
}

user := User{
    Name:    "Alice",
    Friends: []string{"Bob", "Charlie"},
    Config:  map[string]interface{}{"theme": "dark"},
}

cloned := deepclone.Clone(user) // Complete deep copy
Custom Cloning Behavior
type Document struct {
    Title   string
    Content []byte
    Version int
}

// Implement custom cloning logic
func (d Document) Clone() any {
    return Document{
        Title:   d.Title,
        Content: deepclone.Clone(d.Content).([]byte),
        Version: d.Version + 1, // Increment version on clone
    }
}

doc := Document{Title: "My Doc", Version: 1}
cloned := deepclone.Clone(doc) // Version becomes 2

For more examples, see examples/ directory.

⚑ Performance

DeepClone is optimized for performance with:

  • Zero allocations for primitive types
  • Fast paths for common slice/map types
  • Reflection caching for struct types
  • Minimal overhead for complex operations
Benchmark Results

Tested on Apple M3, macOS (darwin/arm64):

Operation Performance Memory Allocations
Primitives (int/string/bool) 2.7-3.6 ns/op 0 B/op 0 allocs/op
Slice (100 ints) 200.6 ns/op 896 B/op 1 allocs/op
Map (100 entries) 4,299 ns/op 3,544 B/op 4 allocs/op
Simple Struct 248.6 ns/op 128 B/op 4 allocs/op
Nested Struct 1,386 ns/op 952 B/op 19 allocs/op
Large Slice (10K ints) 6,709 ns/op 81,920 B/op 1 allocs/op

For detailed benchmarks and comparisons with other libraries, see benchmarks/.

# Run benchmarks
cd benchmarks && go test -bench=. -benchmem

πŸ“– API Reference

Core Function
func Clone[T any](src T) T

Creates a deep copy of any value. The returned value is completely independent of the original.

Custom Cloning Interface
type Cloneable interface {
    Clone() any
}

Implement this interface to provide custom cloning behavior for your types.

πŸ› οΈ Advanced Features

  • Circular Reference Detection: Prevents infinite loops in self-referencing structures
  • Interface Preservation: Maintains original interface types while cloning concrete values
  • Thread Safety: All operations are safe for concurrent use
  • Type Caching: Struct metadata is cached for improved performance on repeated operations

🀝 Contributing

We welcome contributions! Please feel free to:

  • Report bugs
  • Suggest new features
  • Submit pull requests
  • Improve documentation

πŸ“‹ Requirements

  • Go 1.25 or later
  • No external dependencies

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation ΒΆ

Overview ΒΆ

Package deepclone provides high-performance deep cloning functionality for Go.

This package is designed for extreme performance optimization, utilizing Go 1.21+ generics, reflection caching, and careful memory management to achieve zero-allocation hot paths where possible.

Basic Usage:

import "github.com/kaptinlin/deepclone"

// Clone any value with deep copying semantics
dst := deepclone.Clone(src)

// For custom types, implement the Cloneable interface for deep cloning
type MyStruct struct {
    Name string
    Data []int
}

func (m MyStruct) Clone() any {
    return MyStruct{
        Name: m.Name,
        Data: deepclone.Clone(m.Data).([]int), // Deep clone nested data
    }
}

Performance Features:

  • Zero-allocation hot paths for primitive types
  • Reflection result caching for struct types
  • Optimized fast paths for common slice and map types
  • CPU cache-friendly data access patterns

Supported Types:

  • All primitive types (int, string, bool, etc.)
  • Slices, maps, and arrays (with deep cloning of elements)
  • Pointers and pointer chains (with circular reference detection)
  • Structs (with automatic field-by-field deep cloning)
  • Interfaces (with concrete type preservation)
  • Custom types implementing Cloneable interface

Deep Cloning Semantics:

  • All cloning operations perform deep copies by default
  • Nested data structures are recursively cloned
  • Circular references are safely detected and handled
  • Custom types can override default behavior via Cloneable interface

Thread Safety:

  • All cloning operations are thread-safe
  • Internal caches use concurrent-safe mechanisms
  • No global state modifications during cloning

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Clone ΒΆ

func Clone[T any](src T) T

Clone creates a deep copy of the given value. This is the main entry point for the deepclone package.

The function supports all basic Go types and uses optimized paths for common scenarios to achieve maximum performance.

For custom types, implement the Cloneable interface to provide specialized cloning behavior.

Performance characteristics:

  • Zero allocation for primitive types
  • Optimized paths for slices, maps, and common structs
  • Reflection caching for repeated struct types
  • Circular reference detection to prevent infinite loops

Usage:

dst := deepclone.Clone(src)

Types ΒΆ

type Cloneable ΒΆ

type Cloneable interface {
	Clone() any
}

Cloneable interface allows types to implement custom deep cloning behavior. Types implementing this interface will have their Clone method called instead of using the default reflection-based cloning.

The Clone method should return a deep copy of the receiver. It's the implementer's responsibility to ensure all nested data is properly cloned to maintain complete independence from the original.

Example:

type Document struct {
    Title   string
    Content []byte
    Metadata map[string]interface{}
}

func (d Document) Clone() any {
    return Document{
        Title:   d.Title,
        Content: deepclone.Clone(d.Content).([]byte),
        Metadata: deepclone.Clone(d.Metadata).(map[string]interface{}),
    }
}

Directories ΒΆ

Path Synopsis
examples
basic command
Package main demonstrates basic usage of the deepclone library.
Package main demonstrates basic usage of the deepclone library.
circular command
Package main demonstrates handling circular references with the deepclone library.
Package main demonstrates handling circular references with the deepclone library.
custom command
Package main demonstrates custom cloning behavior with the deepclone library.
Package main demonstrates custom cloning behavior with the deepclone library.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL