deepcopy

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2025 License: MIT Imports: 7 Imported by: 0

README

Reflection-based deep copy for Go

Documentation

Overview

Package deepcopy implements the proposal https://go.dev/issue/51520.

Warning: Not largely tested. Use it with care. nolint

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Copy

func Copy[T any](src T, opts ...Option) (dst T)

Copy copies src to dst recursively.

Two values of identical type are deeply copied if one of the following cases apply.

Numbers, bools, strings are deeply copied and have different underlying memory address.

Slice and Array values are deeply copied, including its elements.

Map values are deeply copied for all of its key and corresponding values.

Pointer values are deeply copied for their pointed value, and the pointer points to the deeply copied value.

Struct values are deeply copied for all fields, including exported and unexported.

Interface values are deeply copied if the underlying type can be deeply copied.

There are a few exceptions that may result in a deeply copied value not deeply equal (asserted by DeepEqual(dst, src)) to the source value:

  1. Func values are still refer to the same function
  2. Chan values are replaced by newly created channels
  3. One-way Chan values (receive or read-only) values are still refer to the same channel

Note that while correct uses of Copy do exist, they are not rare. The use of Copy often indicates the copying object does not contain a singleton or is never meant to be copied, such as sync.Mutex, os.File, net.Conn, js.Value, etc. In these cases, the copied value retains the memory representations of the source value but may result in unexpected consequences in follow-up usage, the caller should clear these values depending on their usage context.

To change these predefined behaviors, use provided DeepCopyOption.

Types

type Option

type Option func(opt *copyConfig)

Option represents an option to customize deep copied results.

func DisallowBidirectionalChan

func DisallowBidirectionalChan() Option

DisallowBidirectionalChan returns a DeepCopyOption that disables the behavior of producing new channel when a bidirectional channel is copied.

func DisallowCircular

func DisallowCircular() Option

DisallowCircular returns a DeepCopyOption that disables the behavior of copying circular structures.

func DisallowTypes

func DisallowTypes(val ...any) Option

DisallowTypes returns a DeepCopyOption that disallows copying any types that are in given values.

func DisallowUnexported

func DisallowUnexported() Option

DisallowUnexported returns a DeepCopyOption that disables the behavior of copying unexported fields.

Jump to

Keyboard shortcuts

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