This tool generates deep copy methods for Go structs based on specific annotations.
Install the DeepCopy generator tool using the following command:
go get -u github.com/xsean2020/deep-copy
Use the deep-copy command to generate deep copy methods with custom annotations:
go run -mod=mod github.com/xsean2020/deep-copy --root .
- @Copyable: Marks whether to generate deep copy methods.
- @PtrRecv: Specifies whether the generated method should accept a pointer receiver.
- @Exportedonly=true: Set to true to generate methods only for exported fields.
- @Name: Specify the generated function name.
The generated deep copy methods will respect the specified annotations.
package main
// @copyable
// @exportedonly false
type YourStruct struct {
// Struct fields definition
Field1 string
Field2 int
field3 int // be exported
}
// @copyable
// @ptrrecv false
// @name clone
// @exportedonly true
type AnotherStruct struct {
// Struct fields definition
S *YourStruct
S2 int `deepcopy:"-"` // no export
}
Run Command:
go run -mod=mod github.com/xsean2020/deep-copy --root .
- command out put *_gen_deepcopy.go:
// Code generated by ../deep-copy .; DO NOT EDIT.
package main
// DeepCopy generates a deep copy of *YourStruct
func (o *YourStruct) DeepCopy() *YourStruct {
if o == nil {
return nil
}
var cp YourStruct
var val = *o
cp.Field1 = val.Field1
cp.Field2 = val.Field2
cp.field3 = val.field3
return &cp
}
// clone generates a deep copy of AnotherStruct
func (o AnotherStruct) clone() AnotherStruct {
var cp AnotherStruct
if o.S != nil {
cp.S = o.S.DeepCopy()
}
return cp
}
Feedback and contributions are welcome. Please refer to the contribution guidelines for more information.
This project is licensed under the BSD 3-Clause License