Ad space (banner)
๐ŸŸฃJulia Lessons
Lesson 40 / 68

Shallow copies versus deep copies

This lesson covers the difference between shallow and deep copies in Julia, with the aim of avoiding bugs caused by unintentionally shared data.

Assigning an object made with mutable struct to another variable in fact copies a reference pointing at the same thing. That is a shallow copy, and changing one affects the other.

In the sample code, shallow = original makes shallow point at the same Address instance. Changing it with shallow.city = "Osaka" therefore changes what original.city displays too.

A common early stumble is the bug where "I copied it, but the original changed as well". It happens especially readily with a mutable struct.

In professional work, when you want genuinely independent data you make a deep copy with the deepcopy() function.

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

๐Ÿงช This site can't compile or run Julia 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)