Go Deep vs Shallow Copy Guide

In Golang, deep copy and shallow copy refer to whether the reference type data of an object is copied when copying the object. Here are the methods for deep copy and shallow copy.

Shallow copy:
A shallow copy refers to copying only the values of an object without duplicating reference type data. In Golang, shallow copy can be done using the assignment operator = or the copy function.

Sample code:

package main

import (
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	// 创建一个Person对象
	p1 := Person{Name: "Alice", Age: 20}

	// 使用赋值操作符进行浅拷贝
	p2 := p1

	// 修改p2的Name属性
	p2.Name = "Bob"

	// 打印p1和p2的Name属性
	fmt.Println(p1.Name) // 输出:Alice
	fmt.Println(p2.Name) // 输出:Bob
}

Deep copy:
A deep copy refers to making a duplicate of an object, including copying any reference type data. In Golang, you can use the json.Marshal and json.Unmarshal functions to achieve deep copying.

Sample code:

package main

import (
	"encoding/json"
	"fmt"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	// 创建一个Person对象
	p1 := Person{Name: "Alice", Age: 20}

	// 使用json.Marshal和json.Unmarshal进行深拷贝
	data, _ := json.Marshal(p1)
	var p2 Person
	json.Unmarshal(data, &p2)

	// 修改p2的Name属性
	p2.Name = "Bob"

	// 打印p1和p2的Name属性
	fmt.Println(p1.Name) // 输出:Alice
	fmt.Println(p2.Name) // 输出:Bob
}

It is important to note that when performing deep copying, the member variables of the object must be exportable (i.e. starting with a capital letter), otherwise deep copying cannot be done properly.

bannerAds