Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

copy pointer to a new instance #14

Closed
wangxufire opened this issue Jul 5, 2017 · 2 comments
Closed

copy pointer to a new instance #14

wangxufire opened this issue Jul 5, 2017 · 2 comments

Comments

@wangxufire
Copy link

wangxufire commented Jul 5, 2017

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
Copy link

Did you find any generic deep-copier in golang?

@CrushedPixel
Copy link

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.

@thoas thoas closed this as completed Feb 24, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants