This project is based on the Go language development cloning toolkit and supports shallow and deep copy operations of all types of data in the Go language.
When deep or shallow copy struct type data, you can manipulate exported or unexported fields.
- Provides shallow and deep copy functions.
- Comprehensive,efficient and reusable,supports shallow and deep copies for struct exported and unexported fields.
- Does not depends on any third-party libraries.
- Provide unit test cases for each exported functions.
Install:
go get "github.com/lmlat/go-clone"
Import:
import "github.com/lmlat/go-clone"
Note:
After importing the package, by default all provided functionality is defined in a package named
clone
.
Deep copy the value of a struct type, containing the fields in the struct that are not exported.
type A struct {
name string
Age int
birthday time.Time
hobby []string
}
src := A{"aitao", 100, time.Now(), []string{"ping pong", "badminton", "football"}}
dst := Deep(src).(A)
// When you modify the value of non-reference type, the source data is not affected.
dst.name = "哆啦A梦"
// When you modify the value of reference type, the source data is not affected.
dst.hobby[0] = "乒乓球"
Deep copy the value of a struct pointer type, containing the fields in the strcut that are not exported.
src := &A{"aitao", 100, time.Now(), []string{"ping pong", "badminton", "football"}}
dst := Deep(src).(*A) // deep copy value
Skip copying the specified fields in the struct via the 'ignore' tag:
type B struct {
name string `ignore:"name"`
Age int
birthday time.Time
hobby []string
}
src := &B{"aitao", 100, time.Now(), []string{"ping pong", "badminton", "football"}}
dst := Deep(src).(*B)
Deep copy only the exported fields in the structure:
dst = Deep(src, WithOpFlags(OnlyPublicField)).(A)
// The same effect can be achieved using CopyProperties function.
dst = CopyProperties(src).(C)
Some commonly used operation flags:
- OnlyPublicField:only exported field values in the struct are copied, only struct type values.
- OnlyPrivateField:only field values that are not exported in the struct are copied, only struct type values.
- AllFields:copy all field values in the struct, including exported and unexported fields, only for struct type values.
- DeepString:deep copy string type values.
- DeepFunc:deep copy func type values.
- DeepArray:deep copy array type values.
Some special types of shallow copy processing:
- time.Time
- reflect.Type:The type system of the Go language is static at compile time, meaning that the type information is determined at compile time. Therefore, when dealing with the 'reflect.Type' interface, it is usually not necessary to make a deep copy (' reflect.rtype 'is immutable). Shallow copy the value of a struct type, containing the fields in the struct that are not exported.
src := C{"aitao", 100, time.Now(), []string{"ping pong", "badminton", "football"}}
dst := Shallow(src).(C)