Ad space (banner)
๐ŸนGo Lessons
Lesson 40 / 68

Shallow Copy vs. Deep Copy

In this lesson you will learn the difference between a shallow and a deep copy in Go, so you can avoid bugs caused by unintentionally shared data. This is for anyone searching for "Go shallow copy deep copy".

Assigning a Go struct copies its value, but when it contains a pointer, a map, or a slice, you get a "shallow copy" and the thing being pointed at stays shared with the original.

In the sample code, shallow := original copies the Person struct itself, but the inner Address field is a pointer and still refers to the same object. So setting shallow.Address.City = "Osaka" also changes what original.Address.City prints.

A common stumbling block for beginners is the bug where "I copied it, but the original changed too". It is especially easy to hit when working with structs that contain pointers.

In real-world development, understanding how pointers behave is essential background for writing Go with fewer bugs.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Go directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)