Skip to content
darxnetPublic

About

Generates CopyFrom and Copy methods for Go structs that reuse the destination's memory instead of allocating

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

gocopy

Go Reference Go Coverage

gocopy generates CopyFrom(src) and Copy() methods that make a struct value an independent copy of another — without allocating what the destination already owns.

Why gocopy?

*dst = *src is a shallow copy: every slice and map in dst now shares memory with src, and the first write to one shows up in the other. The deep copy by hand allocates a fresh slice for every field on every call, and goes stale the day a field is added. gocopy writes the method from the struct definition and reuses dst's memory:

// Code generated by gocopy; DO NOT EDIT.

// CopyFrom makes dst an independent copy of src: one bulk copy, then the
// fields that would share memory get dst's own, reusing its capacity.
func (dst *Request) CopyFrom(src *Request) {
	keepData := dst.Data[:0]
	keepInner := dst.Inner

	*dst = *src
	dst.Data = append(keepData, src.Data...)
	if dst.Data == nil && src.Data != nil {
		dst.Data = make([]byte, 0)
	}
	dst.Inner = keepInner
	dst.Inner.CopyFrom(&src.Inner)
}

// Copy returns a new independent copy of src.
func (src *Request) Copy() (dst Request) {
	dst.CopyFrom(src)
	return dst
}

A CopyFrom into a pooled, already-sized dst allocates nothing.

What it does per field

Field Copy
slice append(dst.F[:0], src.F...) — into dst's own array (nil only when src is nil and dst was: see below)
map entry by entry into dst's own map (clear first; a nil dst map is made, a nil src leaves dst empty)
struct with CopyFrom(*T) dst.F.CopyFrom(&src.F)
pointer to struct with CopyFrom(*T) into dst's own object; a nil dst gets a new one, a nil src gives nil
array element by element, when the elements need a copy of their own
slice of slices, maps, structs with CopyFrom or pointers to them element by element into dst's own elements, up to its capacity (a larger src gets a new array); a nil pointer element stays nil
map of slices, maps, structs with CopyFrom or pointers to them each value a new copy (dst's old values are dropped with clear); a nil pointer value stays nil
interface that declares Clone() returning itself (type Shape interface { ...; Clone() Shape }) dst.F = src.F.Clone(), whatever the value inside; a nil src gives nil
everything else (numbers, strings, pointers, other interfaces, chans, funcs, plain structs) assigned as it is
a type parameter T of a generic struct assigned as it is, whatever the type argument (Box[[]byte] shares it)

A non-nil src slice or map gives a non-nil dst one, even when empty, so [] stays [] in JSON. A nil src slice or map empties dst's but leaves it non-nil when it was — dst keeps its memory for the next copy — so after CopyFrom a nil and an empty one are not told apart; Copy starts from a zero dst and keeps them apart.

The rules apply at any depth: [][]byte, map[string][]Inner and [2][3][]byte share nothing with src. A type that contains itself through slices or maps (type Tree []Tree) has no end to copy: such a field needs a tag. Map keys are assigned.

A generic struct gets func (dst *Box[T]) CopyFrom(src *Box[T]); a []T or map[K]V field is still copied as a slice or a map.

Struct tags change the treatment of a field:

Tag Effect
copy:"-" dst keeps its own value
copy:"shallow" assigned as it is, even if it is a slice or a map — on purpose, and visibly
copy:"clone" dst.F = src.F.Clone() for a type with a method Clone() returning its own type, like *tls.Config or http.Header; a nil src gives nil (a type parameter's Clone is called whatever the value)

A field holding a lock must carry one of the two tags. A lock is what go vet copylocks calls one — a type whose pointer is a sync.Locker while the value is not, so a custom noCopy counts — and any other sync or sync/atomic type except an interface (sync.Locker itself is assigned), also inside a nested struct or array, by value. Blank (_) fields are never copied: dst keeps its own.

Two modes

Bulk (the default): dst's own slices, maps and nested values are saved, the struct is assigned in one go, the saved fields are put back and filled from src. The type also gets Copy().

Field by field: a struct that holds a lock or an atomic cannot be assigned as a whole (go vet copylocks), so every field is copied on its own, and there is no Copy(): such a value is not meant to be returned.

The mode is chosen per type, and shown in the comment of the generated method.

Installation

go get -tool github.com/darxnet/gocopy/cmd/gocopy

Requires Go 1.24 (go get -tool). No dependencies: the package is loaded with go list -export and go/importer from the standard library.

Usage

Put the directive next to the type and run go generate:

//go:generate go tool gocopy -type=Request,Response
type Request struct {
	Data  []byte
	Inner Inner
	Cache map[string]int `copy:"-"`
	Mu    sync.Mutex     `copy:"-"`
}

This writes request_copy.gen.go and response_copy.gen.go in the same package. -dir points the generator at another package.

The generator is also a library — gocopy.Load, Package.Generate and Package.GenerateAll — for tools that want the source without the file.

Rules of the generated CopyFrom

  • src and dst must not be the same value or share slices: dst's arrays are overwritten.
  • A nested type's CopyFrom is found by its method set when the generator runs, or because the same run generates it: name all the types of a package in one -type list (one go:generate line), and the output does not depend on their order or on the files already there. A type generated by another directive is seen only once its file exists, so the first go generate and the second could differ.
  • A pointer to the type itself (Next *Node) is copied recursively, from the first run: a long chain costs as much stack, and cyclic data (a ring) never ends — tag such a field copy:"shallow" to share it instead.
  • Pointers other than "pointer to a struct with CopyFrom" are shared with src. That is usually right for references to long-lived objects; for an owned object, give its type a CopyFrom, or tag the field copy:"clone" when the type has its own Clone().

See also

The sibling modules follow the same rule — nothing allocated on the hot path, the zero value ready to use:

  • goshard — sharded, lock-based concurrent map for high-churn data: stores allocate nothing
  • gosync — generic concurrent map with sync.Map semantics and no interface boxing, for read-mostly data
  • goreset — generates Reset() for pooled structs: back to the zero state, memory kept

License

Apache License 2.0. See LICENSE for details.

About

Generates CopyFrom and Copy methods for Go structs that reuse the destination's memory instead of allocating

Topics

Resources

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages