To create a deep copy of a struct using reflection in Go, you can follow the steps below:
import (
"reflect"
)
func DeepCopy(src interface{}) interface{} {
// Get the type of the source struct
srcType := reflect.TypeOf(src)
// Create a new instance of the source struct type
dest := reflect.New(srcType).Elem()
// Get the value of the source struct
srcValue := reflect.ValueOf(src)
// Iterate over the fields of the source struct
for i := 0; i < srcValue.NumField(); i++ {
// Get the field value and type of the source struct
fieldValue := srcValue.Field(i)
fieldType := srcType.Field(i)
// Create a deep copy of the field value
fieldCopy := reflect.New(fieldValue.Type()).Elem()
if fieldValue.Kind() == reflect.Struct {
fieldCopy.Set(reflect.ValueOf(DeepCopy(fieldValue.Interface())))
} else {
fieldCopy.Set(fieldValue)
}
// Set the copied field value in the new struct
dest.FieldByName(fieldType.Name).Set(fieldCopy)
}
// Return the copy of the struct
return dest.Interface()
}
DeepCopy
function and pass the struct instance as an argument:type Person struct {
Name string
Age int
Addr Address
}
type Address struct {
Street string
City string
State string
}
func main() {
p1 := Person{Name: "Alice", Age: 25, Addr: Address{Street: "123 Main St", City: "City1", State: "State1"}}
p2 := DeepCopy(p1).(Person)
fmt.Println(p1) // {Alice 25 {123 Main St City1 State1}}
fmt.Println(p2) // {Alice 25 {123 Main St City1 State1}}
// Modify a field in p2
p2.Name = "Bob"
p2.Addr.City = "City2"
fmt.Println(p1) // {Alice 25 {123 Main St City1 State1}}
fmt.Println(p2) // {Bob 25 {123 Main St City2 State1}}
}
This code will create a deep copy of the Person
struct instance p1
and assign it to p2
. Any modifications made to p2
will not affect p1
, ensuring a true deep copy.