Deep vs Shallow Copy in Golang
In the Go language, deep copy and shallow copy are two concepts related to data duplication.
Shallow copy refers to copying only the reference (address) of a data structure, rather than its actual content. This means that the new and original data structures share the same underlying data, so modifying one will affect the other. In Go language, most built-in types (such as int, string, slice, map, channel, etc.) are shallow copied during assignment operations.
Sample code:
package main
import "fmt"
type Person struct {
Name string
Age int
}
func main() {
p1 := Person{Name: "Alice", Age: 30}
p2 := p1 // 浅拷贝
p1.Name = "Bob"
p1.Age = 40
fmt.Println(p1) // 输出: {Bob 40}
fmt.Println(p2) // 输出: {Bob 40}
}
In the above example, p1 and p2 share the same Person object, so any changes made to p1 will also affect p2.
Deep copy refers to making a complete copy of a data structure layer by layer, including all content, both base data and referenced data. This means that the two data structures, old and new, are completely independent, so modifying one will not affect the other. In Go language, for custom struct types, deep copy can be achieved through methods like using json.Marshal and json.Unmarshal functions for serialization and deserialization, or manually copying each field layer by layer.
Example code:
package main
import (
"encoding/json"
"fmt"
)
type Person struct {
Name string
Age int
}
func main() {
p1 := Person{Name: "Alice", Age: 30}
p2 := deepCopy(p1) // 深拷贝
p1.Name = "Bob"
p1.Age = 40
fmt.Println(p1) // 输出: {Bob 40}
fmt.Println(p2) // 输出: {Alice 30}
}
func deepCopy(src Person) Person {
var dst Person
data, _ := json.Marshal(src)
json.Unmarshal(data, &dst)
return dst
}
In the above examples, by using the json.Marshal and json.Unmarshal functions for serialization and deserialization, a deep copy of the Person object is achieved, ensuring that p1 and p2 are completely independent.