深複製(Deep copy) 淺複製(Shallow copy)

Kimi
2 min readAug 6, 2021

深複製 (Deep Copy)‌

把參考物件的變數指向複製過的新物件, 而不是原有的物件.

值類型的數據, 默認是深複製, Array, Int, String, Float, Boolean, Struct 修改並不會改變原物件‌

Struct 的屬性如果是引用類型的話, 複製的是指針‌

淺複製 (Shallow Copy)

被複製物件的所有變數都的值與原來的物件相同, 對其他物件的引用仍然只指向原來的物件‌

引用類型的數據, 默認是淺複製, Slice, Map, Channel

‌Wiki

https://en.wikipedia.org/wiki/Object_copying

Shallow copy

One method of copying an object is the shallow copy. In that case a new object B is created, and the fields values of A are copied over to B.[3][4][5] This is also known as a field-by-field copy,[6][7][8] field-for-field copy, or field copy.[9] If the field value is a reference to an object (e.g., a memory address) it copies the reference, hence referring to the same object as A does, and if the field value is a primitive type it copies the value of the primitive type. In languages without primitive types (where everything is an object), all fields of the copy B are references to the same objects as the fields of original A. The referenced objects are thus shared, so if one of these objects is modified (from A or B), the change is visible in the other. Shallow copies are simple and typically cheap, as they can be usually implemented by simply copying the bits exactly.‌

Deep copy

A deep copy in progress.

A deep copy having been completed.

An alternative is a deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B. The result is different from the result a shallow copy gives in that the objects referenced by the copy B are distinct from those referenced by A, and independent. Deep copies are more expensive, due to needing to create additional objects, and can be substantially more complicated, due to references possibly forming a complicated graph.‌

Deep copy is a process in which the copying process occurs recursively. It means first constructing a new collection object and then recursively populating it with copies of the child objects found in the original. In case of deep copy, a copy of object is copied in other object. It means that any changes made to a copy of object do not reflect in the original object. In python, this is implemented using “deep copy()” function.

Example in Go

可以看出在淺複製時, obj 和 cloneObj 記憶體位置都一樣 (address:0xc000100300). 所以cloneObj被修改後, 原先到object也會被更改

--

--