问题现象

定义一个对象,对象中嵌套定义了map类型和一个对象,复制原来的对象生成新的对象,改变新对象中map的值和嵌套的对象的值会导致原来的对象的值也被改变。

现象模拟

package main

import (
	"encoding/json"
	"fmt"
)

type StudyCopy struct {
	Name      string
	Reference map[string]interface{}
	Nested    *Nested
}
type Nested struct {
	Name string
}

func NewCopy(parent *StudyCopy) *StudyCopy {
	//copy
	new := *parent
	return &new
}

func NewOldCopy() *StudyCopy {
	return &StudyCopy{
		Name: "oldCopy",
		Reference: map[string]interface{}{
			"test": "testOld",
		},
		Nested: &Nested{
			Name: "oldNested",
		},
	}
}

func ExceNewCopy(copy *StudyCopy, sourceReference map[string]interface{}) *StudyCopy {
	if copy.Reference == nil {
		copy.Reference = make(map[string]interface{})
	}
	if copy.Nested == nil {
		copy.Nested = &Nested{}
	}
	for k, v := range sourceReference {
		copy.Reference[k] = v
	}
	copy.Nested.Name = "newNested"
	return copy
}

func main() {
	//旧对象初始化
	oldCopy := NewOldCopy()
	//新对象初始化
	newCopy := NewCopy(oldCopy)
	sourceReference := map[string]interface{}{
		"test": "testNew",
	}
	newCopy = ExceNewCopy(newCopy, sourceReference)
	jsonO, _ := json.Marshal(oldCopy)
	jsonN, _ := json.Marshal(newCopy)
	fmt.Println("old:", string(jsonO), "new:", string(jsonN))
}

 结果

 解决方案

 涉及到引用和指针的拷贝问题,需要深度拷贝,即new一个新的对象or引用,做值赋值。

代码实现 

 

package main

import (
	"encoding/json"
	"fmt"
)

type StudyCopy struct {
	Name      string
	Reference map[string]interface{}
	Nested    *Nested
}
type Nested struct {
	Name string
}

func NewCopy(parent *StudyCopy) *StudyCopy {
	//copy
	new := *parent
	//引用类型,深度拷贝
	new.Reference = DeepCopy(parent.Reference).(map[string]interface{})
    //指针类型,深度拷贝
	new.Nested = &Nested{
		Name: parent.Name,
	}
	return &new
}

func NewOldCopy() *StudyCopy {
	return &StudyCopy{
		Name: "oldCopy",
		Reference: map[string]interface{}{
			"test": "testOld",
		},
		Nested: &Nested{
			Name: "oldNested",
		},
	}
}

func ExceNewCopy(copy *StudyCopy, sourceReference map[string]interface{}) *StudyCopy {
	if copy.Reference == nil {
		copy.Reference = make(map[string]interface{})
	}
	if copy.Nested == nil {
		copy.Nested = &Nested{}
	}
	for k, v := range sourceReference {
		copy.Reference[k] = v
	}
	copy.Nested.Name = "newNested"
	return copy
}

func DeepCopy(value interface{}) interface{} {
	valueMap, ok := value.(map[string]interface{})
	if !ok {
		return value
	}
	newMap := make(map[string]interface{})
	for k, v := range valueMap {
		newMap[k] = DeepCopy(v)
	}
	return newMap
}

func main() {
	//旧对象初始化
	oldCopy := NewOldCopy()
	//新对象初始化
	newCopy := NewCopy(oldCopy)
	sourceReference := map[string]interface{}{
		"test": "testNew",
	}
	newCopy = ExceNewCopy(newCopy, sourceReference)
	jsonO, _ := json.Marshal(oldCopy)
	jsonN, _ := json.Marshal(newCopy)
	fmt.Println("old:", string(jsonO), "new:", string(jsonN))

结果 

总结

 涉及到指针和引用的拷贝问题,需要多加关注,不做深度拷贝,还有可能会引发并发问题 。