copy pointer to a new instance
Closed this issue · 2 comments
wangxufire commented
type B struct {
id string
}
type A struct {
InsB *B
}
func main() {
insB1 := &B{"test"}
insA1 := &A{insB1}
insA2 := &A{}
deepcopier.Copy(insA1).To(insA2)
fmt.Printf("%+v", insA1)
fmt.Printf("%+v", insA2)
}
I want insA2.InsB is insB2
DeathPoem commented
Did you find any generic deep-copier in golang?
CrushedPixel commented
It seems like https://github.com/mohae/deepcopy has the behaviour you want:
package main
import (
"fmt"
"github.com/mohae/deepcopy"
)
type B struct {
Id string
}
type A struct {
InsB *B
}
func main() {
insB1 := &B{"test"}
insA1 := &A{insB1}
insA2 := deepcopy.Copy(insA1)
fmt.Printf("insA1: %+v | %s\n", insA1, insA1)
fmt.Printf("insA2: %+v | %s\n", insA2, insA2)
}
Console output:
insA1: &{InsB:0xc42000e1f0} | &{%!s(*main.B=&{test})}
insA2: &{InsB:0xc42000e210} | &{%!s(*main.B=&{test})}
Note that I changed the changed the id
field to be exported, as you can only set exported fields via reflection.