deep

package
v0.51.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 10 Imported by: 1 module, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

deep

Functions that reach every level of nested data: deep.Copy makes a copy that shares nothing with the original, and deep.Remove and deep.RemoveFunc delete properties wherever they appear. Both are written for the maps and slices that a JSON or database decoder returns. Part of rosetta.

Go Reference

A shallow copy such as maps.Clone still shares every nested map and slice, so a change to the copy's object changes the original's too. deep.Copy shares none of them, which makes it safe to change a document that something else still reads.

// Copy the activity, so that the stored original keeps its blind recipients
outbound, err := deep.Copy(activity)

if err != nil {
	return err
}

// Remove `bto` and `bcc` from the activity, its object, and everything inside them
if err := deep.Remove(outbound, "bto", "bcc"); err != nil {
	return err
}
What can be copied and searched

Booleans, numbers, strings, time.Time, and every map, slice, and array of them, to any depth. That includes the named types in mapof and sliceof, and types this package has never heard of, such as the MongoDB driver's primitive.M and primitive.A. A struct or array that holds none of the things below, such as the driver's ObjectID, Decimal128, and Timestamp, counts as a simple value. A copy keeps the type of every container, and a nil map or slice stays nil.

deep.Copy returns the type it was given, so a map[string]any comes back as a map[string]any with no type assertion. An untyped nil has no type to return, so a literal is written as deep.Copy[any](nil).

What is refused

A pointer, function, channel, or a struct that holds a map, slice, pointer, or interface is an error in both functions, wherever it is nested. A copy that still shared a pointer would not be a deep copy, and a property left behind inside a struct would go unnoticed. That rules out the driver's primitive.D, which is a slice of such structs. The one pointer both functions follow is a *sliceof.Any, which is how schema stores a new list. A type can opt in by implementing deep.Copier or deep.Remover:

// Copy returns a deep copy of this Envelope. It is given its own depth, and passes
// depth+1 for the value it holds, which is what stops a value that contains itself.
func (envelope *Envelope) Copy(depth int) (any, error) {

	body, err := deep.CopyWithDepth(envelope.Body, depth+1)

	if err != nil {
		return nil, err
	}

	return &Envelope{Body: body}, nil
}

deep.Remove changes the value it is given, so copy first when the original must survive. If it returns an error, some names may already be gone and others not, so a value that failed must not be used as if it were clean.

Choosing what to remove

deep.Remove matches whole, case-sensitive property names. deep.RemoveFunc takes a deep.Matcher, a function that is asked about each property name, for every other rule:

// Remove every property in a reserved namespace
err := deep.RemoveFunc(document, deep.HasPrefix("emissary:", "x-"))

// Combine rules
err = deep.RemoveFunc(document, deep.AnyOf(deep.Named("bto", "bcc"), deep.HasPrefix("x-")))

// Or write one
err = deep.RemoveFunc(document, func(name string) bool {
	return strings.EqualFold(name, "bcc")
})

deep.Named, deep.HasPrefix, and deep.AnyOf are the Matchers that come with the package. deep.HasPrefix ignores an empty prefix, which would otherwise match every property.

Maximum depth

Both functions stop with an error once they are 10,000 levels deep, which is the deepest document Go's JSON decoder will read. The limit is what stops a map or slice that contains itself, which would otherwise never end.

Documentation

Overview

Package deep copies and searches nested data: the maps and slices that a JSON or database decoder returns, at every level of nesting.

Copy returns a copy that shares no map or slice with the original, so that a caller can change one without changing the other. Every container in the copy keeps its own type, and the copy is returned as the type that Copy was given.

Remove deletes the named properties from every map within a value, in place. RemoveFunc does the same for the properties that a Matcher selects, such as HasPrefix. To leave the original untouched, Copy it first and Remove from the copy.

Both functions list the common types for speed, and reach every other map, slice, and array by reflection. A value that neither can walk, such as a function or a struct that holds a map, is an error, unless it implements Copier or Remover.

Both stop with an error at 10,000 levels of nesting, which is what stops a map or slice that contains itself.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Copy

func Copy[T any](original T) (T, error)

Copy returns a deep copy of a value, which shares no map or slice with the original. A value that it cannot copy, such as a function or a struct that holds a map, is an error.

Example

ExampleCopy copies a document, then changes the copy without changing the original

original := map[string]any{
	"type": "Note",
	"to":   []any{"alice"},
}

duplicate, err := Copy(original)

if err != nil {
	fmt.Println(err)
	return
}

duplicate["to"].([]any)[0] = "bob"

fmt.Println(original["to"])
fmt.Println(duplicate["to"])
Output:
[alice]
[bob]

func CopyWithDepth

func CopyWithDepth[T any](original T, depth int) (T, error)

CopyWithDepth continues a copy that is already under way, at the given level of nesting. It is for a Copier, which passes its own depth plus one for each value that it holds.

func Remove

func Remove(value any, propertyNames ...string) error

Remove deletes the named properties from every map within a value, changing it in place. A value that it cannot search, such as a function or a struct that holds a map, is an error.

Example

ExampleRemove deletes two property names from every level of a document

document := map[string]any{
	"type": "Create",
	"bcc":  []any{"carol"},
	"object": map[string]any{
		"type": "Note",
		"bto":  "dave",
	},
}

if err := Remove(document, "bto", "bcc"); err != nil {
	fmt.Println(err)
	return
}

fmt.Println(document)
Output:
map[object:map[type:Note] type:Create]

func RemoveFunc

func RemoveFunc(value any, match Matcher) error

RemoveFunc deletes every property that the Matcher selects from every map within a value, changing it in place. It returns the same errors as Remove, and one for a nil Matcher.

Example

ExampleRemoveFunc deletes every property in a reserved namespace

document := map[string]any{
	"type":           "Note",
	"emissary:token": "secret",
	"tag":            []any{map[string]any{"name": "go", "x-internal": true}},
}

if err := RemoveFunc(document, HasPrefix("emissary:", "x-")); err != nil {
	fmt.Println(err)
	return
}

fmt.Println(document)
Output:
map[tag:[map[name:go]] type:Note]

func RemoveWithDepth

func RemoveWithDepth(value any, depth int, match Matcher) error

RemoveWithDepth continues a removal that is already under way, at the given level of nesting. It is for a Remover, which passes its own depth plus one for each value it holds.

Types

type Copier

type Copier interface {
	Copy(depth int) (any, error)
}

Copier is implemented by a value that returns a deep copy of itself. It copies what it holds with CopyWithDepth and depth+1.

type Matcher

type Matcher func(name string) bool

Matcher returns TRUE for the name of a property that Remove should delete

func AnyOf

func AnyOf(matchers ...Matcher) Matcher

AnyOf returns a Matcher for properties that at least one of the given Matchers selects. A nil Matcher is ignored.

Example

ExampleAnyOf combines the Matchers that come with the package with one of the caller's own

match := AnyOf(
	Named("bto", "bcc"),
	HasPrefix("x-"),
	func(name string) bool { return strings.HasSuffix(name, "_private") },
)

fmt.Println(match("bcc"), match("x-debug"), match("notes_private"), match("to"))
Output:
true true true false

func HasPrefix

func HasPrefix(prefixes ...string) Matcher

HasPrefix returns a Matcher for properties whose names begin with one of the given prefixes. An empty prefix is ignored.

func Named

func Named(names ...string) Matcher

Named returns a Matcher for properties with one of the given names. Names are matched whole, and upper and lower case letters are different.

type Remover

type Remover interface {
	Remove(depth int, match Matcher) error
}

Remover is implemented by a value that deletes the matching properties from itself. It searches what it holds with RemoveWithDepth and depth+1.

Jump to

Keyboard shortcuts

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