Deepcopy: Difference between revisions

41,991 bytes added ,  5 months ago
m
(Lingo added)
m (→‎{{header|Wren}}: Minor tidy)
 
(46 intermediate revisions by 25 users not shown)
Line 19:
* Suitable links to external documentation for common libraries.
<br><br>
 
=={{header|6502 Assembly}}==
Deep copying is very simple on the 6502 - just load a value from memory and store it somewhere else.
<syntaxhighlight lang="6502asm">LDA $00 ;read the byte at memory address $00
STA $20 ;store it at memory address $20</syntaxhighlight>
 
Now, anything you do to the byte at <tt>$00</tt> won't affect the byte at <tt>$20</tt>.
<syntaxhighlight lang="6502asm">LDA $00 ;read the byte at memory address $00
STA $20 ;store it at memory address $20
INC $00 ;add 1 to the original
CMP $00 ;compare the copy to the original (we could have done LDA $20 first but they're the same value so why bother)
BNE notEqual ;this branch will be taken.</syntaxhighlight>
 
There is no built-in <code>memcpy()</code> function but it doesn't take much effort to create one. This version can copy up to 256 bytes of memory:
<syntaxhighlight lang="6502asm">;input:
;$00,$01 = pointer to source
;$07,$08 = pointer to destination
;X = bytes to copy
;(the memory addresses are arbitrary, but each pair of input addresses MUST be consecutive or this won't work.)
memcpy:
LDY #0
memcpy_again:
lda ($00),y
sta ($07),y
iny
dex
bne memcpy_again
rts</syntaxhighlight>
 
 
=={{header|Aime}}==
<langsyntaxhighlight lang="aime">list L1, L2;
 
# Lists are heterogeneous:
Line 52 ⟶ 81:
o_text(l_query(l_query(L2, 2), 1));
o_text(l_query(l_query(L1, 2), 1));
o_byte('\n');</langsyntaxhighlight>
{{out}}
<pre>deepcopy
deepcopy</pre>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">x: #[
name: "John"
surname: "Doe"
age: 34
hobbies: [
"Cycling",
"History",
"Programming",
"Languages",
"Psychology",
"Buddhism"
]
sayHello: function [][
print "Hello there!"
]
]
 
print ["Name of first person:" x\name]
 
y: new x
y\name: "Jane"
 
print ["Name of first person:" x\name]
print ["Name of second person:" y\name]</syntaxhighlight>
 
{{out}}
 
<pre>Name of first person: John
Name of first person: John
Name of second person: Jane</pre>
 
=={{header|AutoHotkey}}==
{{works with|AutoHotkey L}}
http://www.autohotkey.com/board/topic/85201-array-deep-copy-treeview-viewer-and-more/
<langsyntaxhighlight lang="autohotkey">DeepCopy(Array, Objs=0)
{
If !Objs
Line 72 ⟶ 134:
: DeepCopy(Val,Objs) ; Otherwise, clone this sub-array
Return Obj
}</langsyntaxhighlight>
 
=={{header|AWK}}==
AWK's only data structure is the associative array, and it doesn't allow nested associative arrays (POSIX). Thus:
<syntaxhighlight lang="awk">BEGIN {
for (elem in original)
copied[elem] = original[elem]
}</syntaxhighlight>
 
=={{header|Babel}}==
Line 80 ⟶ 149:
Here is an example of shallow-copy - modifying one object modifies both because they are really just references to one underlying object:
 
<langsyntaxhighlight lang="babel">babel> [1 2 3] dup dup 0 7 0 1 move sd !
---TOS---
[val 0x7 0x2 0x3 ]
[val 0x7 0x2 0x3 ]
---BOS---</langsyntaxhighlight>
 
Deep-copy is proved by the ability to separately modify two objects:
 
<langsyntaxhighlight lang="babel">babel> clear [1 2 3] dup cp dup 0 7 0 1 move sd !
---TOS---
[val 0x7 0x2 0x3 ]
[val 0x1 0x2 0x3 ]
---BOS---</langsyntaxhighlight>
 
You can deep-copy any pure-Babel object with cp. Here is a list-of-lists, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> ((1 2) (3 4) (5 6)) cp
babel> {lsnum !} each
( 1 2 )
( 3 4 )
( 5 6 )</langsyntaxhighlight>
 
Here is a list-of-maps, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> ([map "foo" 3 "bar" 17] [map "foo" 4 "bar" 18] [map "foo" 5 "bar" 19] [map "foo" 0 "bar" 20]) cp
babel> 2 ith "bar" lumap ! itod say !
19</langsyntaxhighlight>
 
Here is Babel code, we copy it using cp:
 
<langsyntaxhighlight lang="babel">babel> { { 1 randlf 100 rem itod << " " << } 20 times } cp
babel> eval
86 51 50 43 82 76 13 78 33 45 11 35 84 25 80 36 33 81 43 24</langsyntaxhighlight>
 
=={{header|C sharp}}==
===Structures without pointers===
<lang csharp>using System;
Structures without pointers can be copied like ''standard'' C variables such as int, float, char etc. The level of nesting is irrelevant. As the following implementation shows, a simple assignment is enough :
<syntaxhighlight lang="c">
#include<stdio.h>
 
typedef struct{
int a;
}layer1;
 
typedef struct{
layer1 l1;
float b,c;
}layer2;
 
typedef struct{
layer2 l2;
layer1 l1;
int d,e;
}layer3;
 
void showCake(layer3 cake){
printf("\ncake.d = %d",cake.d);
printf("\ncake.e = %d",cake.e);
printf("\ncake.l1.a = %d",cake.l1.a);
printf("\ncake.l2.b = %f",cake.l2.b);
printf("\ncake.l2.l1.a = %d",cake.l2.l1.a);
}
 
int main()
{
layer3 cake1,cake2;
cake1.d = 1;
cake1.e = 2;
cake1.l1.a = 3;
cake1.l2.b = 4;
cake1.l2.l1.a = 5;
printf("Cake 1 is : ");
showCake(cake1);
cake2 = cake1;
cake2.l2.b += cake2.l2.l1.a;
printf("\nCake 2 is : ");
showCake(cake2);
return 0;
}
</syntaxhighlight>
Output:
<pre>
Cake 1 is :
cake.d = 1
cake.e = 2
cake.l1.a = 3
cake.l2.b = 4.000000
cake.l2.l1.a = 5
Cake 2 is :
cake.d = 1
cake.e = 2
cake.l1.a = 3
cake.l2.b = 9.000000
cake.l2.l1.a = 5
</pre>
===Structures with pointers===
Structures with pointers which are usually used to represent data structures such as Linked lists, Stacks, Trees, Graphs etc. have to be copied element by element. A simple assignment as in the above example will not be a copy at all. It will be two pointers pointing towards the same memory location.
<syntaxhighlight lang="c">
#include<stdlib.h>
#include<stdio.h>
 
typedef struct elem{
int data;
struct elem* next;
}cell;
 
typedef cell* list;
 
void addToList(list *a,int num){
list temp, holder;
if(*a==NULL){
*a = (list)malloc(sizeof(cell));
(*a)->data = num;
(*a)->next = NULL;
}
else{
temp = *a;
while(temp->next!=NULL)
temp = temp->next;
holder = (list)malloc(sizeof(cell));
holder->data = num;
holder->next = NULL;
temp->next = holder;
}
}
 
list copyList(list a){
list b, tempA, tempB, temp;
if(a!=NULL){
b = (list)malloc(sizeof(cell));
b->data = a->data;
b->next = NULL;
tempA = a->next;
tempB = b;
while(tempA!=NULL){
temp = (list)malloc(sizeof(cell));
temp->data = tempA->data;
temp->next = NULL;
tempB->next = temp;
tempB = temp;
tempA = tempA->next;
}
}
return b;
}
 
void printList(list a){
list temp = a;
while(temp!=NULL){
printf("%d,",temp->data);
temp = temp->next;
}
printf("\b");
}
 
int main()
{
list a,b;
int i;
for(i=1;i<=5;i++)
addToList(&a,i);
printf("List a is : ");
printList(a);
b = copyList(a);
free(a);
printf("\nList a destroyed, List b is : ");
printList(b);
return 0;
}
</syntaxhighlight>
Output:
<pre>
List a is : 1,2,3,4,5,
List a destroyed, List b is : 1,2,3,4,5,
</pre>
 
=={{header|C sharp|C#}}==
<syntaxhighlight lang="csharp">using System;
 
namespace prog
Line 142 ⟶ 378:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
 
In C++ a type defines its own copy semantics. The standard containers copy all of their elements by value
including elements that are complex or are themselves containers. However if the container contains pointers, the
pointers themselves are copied and will continue to point to the original elements. The example below does not use
any pointers.
 
<syntaxhighlight lang="cpp">
#include <array>
#include <iostream>
#include <list>
#include <map>
#include <vector>
 
int main()
{
// make a nested structure to copy - a map of arrays containing vectors of strings
auto myNumbers = std::vector<std::string>{"one", "two", "three", "four"};
auto myColors = std::vector<std::string>{"red", "green", "blue"};
auto myArray = std::array<std::vector<std::string>, 2>{myNumbers, myColors};
auto myMap = std::map<int, decltype(myArray)> {{3, myArray}, {7, myArray}};
 
// make a deep copy of the map
auto mapCopy = myMap;
 
// modify the copy
mapCopy[3][0][1] = "2";
mapCopy[7][1][2] = "purple";
std::cout << "the original values:\n";
std::cout << myMap[3][0][1] << "\n";
std::cout << myMap[7][1][2] << "\n\n";
 
std::cout << "the modified copy:\n";
std::cout << mapCopy[3][0][1] << "\n";
std::cout << mapCopy[7][1][2] << "\n";
}</syntaxhighlight>
{{out}}
<pre>the original values:
two
blue
 
the modified copy:
2
purple
</pre>
 
=={{header|Common Lisp}}==
Line 155 ⟶ 438:
For instance <code>#42=(a b)</code> denotes the list <code>(a b)</code> and furthermore, it associates it with the number 42. Then, later in the same form, #42# denotes an additional occurence of the same <code>(a b)</code> object. So for instance, a cons cell whose <code>car</code> is 1, and whose <code>cdr</code> points back to that cons cell is written <code>#1=(1 . #1#)</code>.
 
<langsyntaxhighlight lang="lisp">$ clisp -q
[1]> (setf *print-circle* t)
T
Line 161 ⟶ 444:
#1=(1 . #1#)
[3]> (read-from-string "#1=(1 . #1#)") ;; read it from a string
#1=(1 . #1#) ;; a similar circular list is returned</langsyntaxhighlight>
 
=={{header|Déjà Vu}}==
<langsyntaxhighlight lang="dejavu">local :(copy-action) {}
 
(copy-action)!list obj cache:
Line 215 ⟶ 498:
 
!. C
!. D</langsyntaxhighlight>
{{out}}
<pre>{ :foo [ "bar" ] [ ] [ & 1 2 & 3 4 ] }
Line 225 ⟶ 508:
[ [ [ [ [...] 7 ] 7 ] 7 ] 7 ]
[ [ [ [ [...] ] ] ] ]</pre>
=={{header|Delphi}}==
{{libheader| System.TypInfo}}
<syntaxhighlight lang="delphi">
program DeepCopyApp;
 
{$APPTYPE CONSOLE}
 
uses
System.TypInfo;
 
type
TTypeA = record
value1: integer;
value2: char;
value3: string[10];
value4: Boolean;
function DeepCopy: TTypeA;
end;
 
{ TTypeA }
 
function TTypeA.DeepCopy: TTypeA;
begin
CopyRecord(@result, @self, TypeInfo(TTypeA));
end;
 
var
a, b: TTypeA;
 
begin
a.value1 := 10;
a.value2 := 'A';
a.value3 := 'OK';
a.value4 := True;
 
b := a.DeepCopy;
a.value1 := 20;
a.value2 := 'B';
a.value3 := 'NOK';
a.value4 := False;
 
Writeln('Value of "a":');
Writeln(a.value1);
Writeln(a.value2);
Writeln(a.value3);
Writeln(a.value4);
 
Writeln(#10'Value of "b":');
Writeln(b.value1);
Writeln(b.value2);
Writeln(b.value3);
Writeln(b.value4);
readln;
end.</syntaxhighlight>
{{out}}
<pre>Value of "a":
20
B
NOK
FALSE
 
Value of "b":
10
A
OK
TRUE</pre>
 
=={{header|E}}==
Line 230 ⟶ 579:
In E, serialization is generalized to transforming object graphs from one representation to another. Deep copying, therefore, consists of transforming a live object graph into a live object graph, by connecting <code>deSubgraphKit</code>'s output to its input. No intermediate serialized form is needed.
 
<langsyntaxhighlight lang="e">def deSubgraphKit := <elib:serial.deSubgraphKit>
def deepcopy(x) {
return deSubgraphKit.recognize(x, deSubgraphKit.makeBuilder())
}</langsyntaxhighlight>
 
As befits a serialization system, this deep copy may operate on any serializable structure, whether standard or user-defined, and the structure may contain cycles.
 
<langsyntaxhighlight lang="e">? def x := ["a" => 1, "b" => [x].diverge()]
# value: ["a" => 1, "b" => [<***CYCLE***>].diverge()]
 
Line 258 ⟶ 607:
 
? x["b"][0] == x
# value: true</langsyntaxhighlight>
 
(<code>.diverge()</code> produces mutable data structures, and <code>&lt;***CYCLE***></code> is what is printed when printing some object meets itself again.)
Line 265 ⟶ 614:
 
=={{header|Erlang}}==
 
Until somebody explains how to create cyclic data structures in Erlang I can show heterogeneous data.
All values in Erlang are immutable and garbage collected, so copying is meaningless. Moreover, it's impossible to create cyclic data structures in Erlang, due to the absence of a <code>let rec</code> construct (and the fact that all values are immutable).
 
Data is copied when sent from one Erlang (lightweight) processes to another, because each process manages it's own memory. This is an implementation detail and is not part of the language semantics.
 
An exception is "large binaries", which can be shared between Erlang processes, and sub-binaries which can reference larger binaries. These can be copied using <code>binary:copy/1</code> to free the memory of the referenced larger binary if it has no other references. This function is provided with [https://www.erlang.org/doc/man/binary.html#copy-1 a note in the reference manual] indicating that this is usually not what you want. Here is an example though:
 
{{out}}
<pre>
1> A = <<"abcdefghijklmnopqrstuvwxyz">>.
16> D.
<<"abcdefghijklmnopqrstuvwxyz">>
{dict,4,16,16,8,80,48,
2> B = <<A/binary, A/binary, A/binary, A/binary>>.
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
<<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">>
{{[["qwe",49,50,51],[p|<0.32.0>]],
3> <<_:10/binary, C:80/binary, _/binary>> = B.
[[a|b]],
<<"abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz">>
[],[],[],[],[],[],[],[],[],
4> C.
[[1|2]],
<<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">>
[],[],[],[]}}}
5> byte_size(C).
[],[],[],[],[],[],[],[],[],
80
[[1|2]],
6> binary:referenced_byte_size(C).
[],[],[],[]}}}
104
17> D2 = D.
7> C2 = binary:copy(C).
18> D2.
<<"klmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijkl">>
{dict,4,16,16,8,80,48,
8> C2 == C.
{[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]},
true
{{[["qwe",49,50,51],[p|<0.32.0>]],
9> binary:referenced_byte_size(C2).
[[a|b]],
80
[],[],[],[],[],[],[],[],[],
</pre>
[[1|2]],
 
[],[],[],[]}}}
=={{header|Factor}}==
It's possible to create deep copies with <code>[ clone ] deep-map</code>, though this suffers from the limitation that it will hang indefinitely on circularities. We can even do this with tuples, since named tuples allow tuples to be treated like arrays. The following is a demonstration of deep copying an object in this manner.
{{works with|Factor|0.99 2019-10-06}}
<syntaxhighlight lang="factor">USING: accessors arrays io kernel named-tuples prettyprint
sequences sequences.deep ;
 
! Define a simple class
TUPLE: foo bar baz ;
 
! Allow instances of foo to be modified like an array
INSTANCE: foo named-tuple
 
! Create a foo object composed of mutable objects
V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa
 
! create a copy of the reference to the object
dup
 
! create a deep copy from this copy
>array [ clone ] deep-map T{ foo } like
 
! print them both
"Before modification:" print [ [ . ] bi@ ] 2keep nl
 
! modify the deep copy
[ -1 suffix! ] change-bar
 
! print them both again
"After modification:" print [ . ] bi@</syntaxhighlight>
{{out}}
<pre>
Before modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
 
After modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 -1 } } { baz V{ 4 5 6 } } }
</pre>
 
Another way to make deep copies is by serializing an object to a byte array and then deserializing it back to an object. This has the advantage of preserving circularities, but it doesn't work on non-serializable objects (such as continuations).
<syntaxhighlight lang="factor">! Create a foo object composed of mutable objects
V{ 1 2 3 } V{ 4 5 6 } [ clone ] bi@ foo boa
 
! create a copy of the reference to the object
dup
 
! create a deep copy from this copy
object>bytes bytes>object
 
! print them both
"Before modification:" print [ [ . ] bi@ ] 2keep nl
 
! modify the deep copy
[ -99 suffix! ] change-bar
 
"After modification:" print [ . ] bi@</syntaxhighlight>
{{out}}
<pre>
Before modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
 
After modification:
T{ foo { bar V{ 1 2 3 } } { baz V{ 4 5 6 } } }
T{ foo { bar V{ 1 2 3 -99 } } { baz V{ 4 5 6 } } }
</pre>
 
 
=={{header|FreeBASIC}}==
{{trans|PureBasic}}
<syntaxhighlight lang="freebasic">
Type DeepCopy
value1 As Integer
value2 As String * 1
value3 As String
value4 As Boolean
value5 As Double
End Type
Dim As DeepCopy a, b
 
a.value1 = 10
a.value2 = "A"
a.value3 = "OK"
a.value4 = True
a.value5 = 1.985766472453666
 
b = a
a.value1 = 20
a.value2 = "B"
a.value3 = "NOK"
a.value4 = False
a.value5 = 3.148556644245367
 
Print !"Valor de \"a\":"
Print a.value1
Print a.value2
Print a.value3
Print a.value4
Print a.value5
 
Print !"\nValor \"b\":"
With b
Print .value1
Print .value2
Print .value3
Print .value4
Print .value5
End With
Sleep
</syntaxhighlight>
{{out}}
<pre>
Valor de "a":
20
B
NOK
false
3.148556644245367
 
Valor de "b":
10
A
OK
true
1.985766472453666
</pre>
 
=={{header|FutureBasic}}==
Translation of FreeBasic
<syntaxhighlight lang="futurebasic">
include "NSLog.incl"
 
begin record DeepCopy
NSInteger value1
CFStringRef value2
CFStringRef value3
Boolean value4
double value5
end record
 
local fn DoDeepCopy
DeepCopy a, b
a.value1 = 10
a.value2 = @"A"
a.value3 = @"Okay"
a.value4 = YES
a.value5 = 1.985766472453666
b = a
b.value1 = 20
b.value2 = @"B"
b.value3 = @"Not Okay"
b.value4 = NO
b.value5 = 3.148556644245367
NSLog( @"\nValue of 'a':" )
NSLog( @"a.value1: %ld", a.value1 )
NSLog( @"a.value2: %@", a.value2 )
NSLog( @"a.value3: %@%", a.value3 )
NSLog( @"b.value4: %@", fn BoolString( a.value4 ) )
NSLog( @"a.value5: %.15f", a.value5 )
NSLog( @"\nValue of 'b':" )
NSLog( @"b.value1: %ld", b.value1 )
NSLog( @"b.value2: %@", b.value2 )
NSLog( @"b.value3: %@%", b.value3 )
NSLog( @"b.value4: %@", fn BoolString( b.value4 ) )
NSLog( @"b.value5: %.15f", b.value5 )
end fn
 
fn DoDeepCopy
 
HandleEvents
</syntaxhighlight>
{{output}}
<pre>
Value of 'a':
a.value1: 10
a.value2: A
a.value3: Okay
b.value4: YES
a.value5: 1.985766472453666
 
Value of 'b':
b.value1: 20
b.value2: B
b.value3: Not Okay
b.value4: NO
b.value5: 3.148556644245367
 
</pre>
 
=={{header|Go}}==
Go does not have direct support for deep copy. To make deep copies of specific data structures, it is most efficient to write your own copy function and just copy what needs to be copied.
 
<lang go>package main
'''Heterogeneous:'''
<syntaxhighlight lang="go">package main
 
import "fmt"
Line 328 ⟶ 877:
fmt.Println(c1) // show changes
fmt.Println(c2) // show copy unaffected
}</langsyntaxhighlight>
Output:
<pre>
Line 336 ⟶ 885:
&{1 one [117 110 105 116] map[1:true]}
</pre>
'''Cyclic:'''
If you need a generalized deep copy, one can be cobbled with an os.Pipe and the gob package, which does type safe serialization. The deepcopy function shown below works on arbitrary data with a few limitations. It handles data types with recursive or cyclic definitions, but does not handle cycles in the data itself. For example, it handles a linked list, but not a ring data structure. Another limitation is that struct fields must be exported. (That is, fields must start with an upper case letter. This makes the field visible outside the package.)
 
<lang go>package main
DIY here requires you to code a traversal algorithm.
<syntaxhighlight lang="go">package main
 
import "fmt"
 
// a type that allows cyclic structures
type node []*node
 
// recursively print the contents of a node
func (n *node) list() {
if n == nil {
fmt.Println(n)
return
}
listed := map[*node]bool{nil: true}
var r func(*node)
r = func(n *node) {
listed[n] = true
fmt.Printf("%p -> %v\n", n, *n)
for _, m := range *n {
if !listed[m] {
r(m)
}
}
}
r(n)
}
 
// construct a deep copy of a node
func (n *node) ccopy() *node {
if n == nil {
return n
}
cc := map[*node]*node{nil: nil}
var r func(*node) *node
r = func(n *node) *node {
c := make(node, len(*n))
cc[n] = &c
for i, m := range *n {
d, ok := cc[m]
if !ok {
d = r(m)
}
c[i] = d
}
return &c
}
return r(n)
}
 
func main() {
a := node{nil}
c := &node{&node{&a}}
a[0] = c
c.list()
cc := c.ccopy()
fmt.Println("copy:")
cc.list()
fmt.Println("original:")
c.list()
}</syntaxhighlight>
{{out}}
<pre>
0xc42000a4a0 -> [0xc42000a4c0]
0xc42000a4c0 -> [0xc42000a480]
0xc42000a480 -> [0xc42000a4a0]
copy:
0xc42000a580 -> [0xc42000a5a0]
0xc42000a5a0 -> [0xc42000a5c0]
0xc42000a5c0 -> [0xc42000a580]
original:
0xc42000a4a0 -> [0xc42000a4c0]
0xc42000a4c0 -> [0xc42000a480]
0xc42000a480 -> [0xc42000a4a0]
</pre>
'''General heterogeneous:'''
 
If you still want a generalized deep copy, one can be cobbled with an os.Pipe and the gob package, which does type safe serialization. The deepcopy function shown below works on arbitrary data with a few limitations. It handles data types with recursive or cyclic definitions, but does not handle cycles in the data itself. For example, it handles a linked list, but not a ring data structure. Another limitation is that struct fields must be exported. (That is, fields must start with an upper case letter. This makes the field visible outside the package.)
<syntaxhighlight lang="go">package main
 
import (
Line 398 ⟶ 1,026:
// show that copy is unaffected
fmt.Println(l2)
}</langsyntaxhighlight>
Output:
<pre>
Line 406 ⟶ 1,034:
(a b)
</pre>
A final limitation to mention of the technique above is the unnecessary overhead of serialization and piping. Using the reflect package, it would be possible to write a generalized deep copy function in Go with fewer limitations. You could copy data directly without going through a pipe, for example, and you could code an algorithm to detect and properly handle cyclic data. Estimated LOC is about 500, and not recommended when a simpler solution will do.
 
=={{header|Icon}} and {{header|Unicon}}==
Line 414 ⟶ 1,041:
The code requires modification to run under Icon as Unicon extended key(X) to operate on lists and records not just tables.
 
<langsyntaxhighlight Uniconlang="unicon">procedure deepcopy(A, cache) #: return a deepcopy of A
local k
 
Line 437 ⟶ 1,064:
}
return .cache[A]
end</langsyntaxhighlight>
 
The following code demonstrates deepcopy usage and that the resulting structure is different from the original by comparing assignment, copy, and deepcopy.
 
<langsyntaxhighlight Iconlang="icon">link printf,ximage
 
procedure main()
Line 494 ⟶ 1,121:
procedure showequiv(x,y) #: show (non-)equivalence of two values
return printf(" %i %s %i\n",x,if x === y then "===" else "~===",y)
end</langsyntaxhighlight>
 
{{libheader|Unicon Code Library}}
Line 551 ⟶ 1,178:
L11[7] := R_Class1__state_2
...</pre>
 
 
=={{header|Insitux}}==
 
It is impossible to have cyclical structures in Insitux, and values are immutable.
 
<syntaxhighlight lang="insitux">> (var x [1 2 [3 4]])
[1 2 [3 4]]
 
> (var y x)
[1 2 [3 4]]
 
> (var x "something else")
something else
 
> y
[1 2 [3 4]]</syntaxhighlight>
 
=={{header|J}}==
Line 556 ⟶ 1,200:
J uses pass by value semantics (typically implemented as copy on write) so Deepcopy is trivial -- values inside the language are immutable.
 
<langsyntaxhighlight lang="j"> a=:b=: 2 2 2 2 2 NB. two copies of the same array
b=: 3 (2)} b NB. modify one of the arrays
b
2 2 3 2 2
a
2 2 2 2 2</langsyntaxhighlight>
 
That said, J can reference values outside the language. But Deepcopy of those values is, by definition, outside the scope of the language. Usually, bringing the values into the language is sufficient.
 
Another possible exception would be classes and objects (which are not values but collections of references to values). But as a general rule copying of an object should be delegated to the object itself rather than imposed from the outside. Also, "deepcopy" violates the Law of Demeter as well as the concept of black-box reuse -- if you need deepcopy in J, you probably should not be representing your data structure as objects.
 
=={{header|Java}}==
Deep copy can be performed several ways.
<ol>
<li>Immutable Objects. Do not perform the deep copy, use immutable objects. If an object is immutable, and hence unchangeable, then a deep copy is not needed. However, this task is about deep copy, so we will continue with the demonstration.</li>
<li>Copy Constructor. Use a copy constructor to make a duplicate of the object. This is not a feature of Java, but a design pattern.</li>
<li>Object Serialization. Java supports serialization of an object to a byte stream using the <code>Serializable</code> interface. However, there are security concerns with this methodology. See the various Internet articles.</li>
<li>Object Clone. Java supports cloning of an object using the <code>Cloneable</code> interface. As with serialization, there are security concerns with this methodology. See the various Internet articles.</li>
</ol>
 
Copy constructor, object serialization, and object clone are demonstrated below.
<syntaxhighlight lang="java">
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
public class DeepCopy {
 
public static void main(String[] args) {
Person p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
Person p2 = p1;
System.out.printf("Demonstrate shallow copy. Both are the same object.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on both objects is changed.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
p1 = new Person("Clark", "Kent", new Address("1 World Center", "Metropolis", "NY", "010101"));
p2 = new Person(p1);
System.out.printf("%nDemonstrate copy constructor. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
 
p2 = (Person) deepCopy(p1);
System.out.printf("%nDemonstrate serialization. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
p2 = (Person) p1.clone();
System.out.printf("%nDemonstrate cloning. Object p2 is a deep copy of p1.%n");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
System.out.printf("Set city on person 2. City on objects is different.%n");
p2.getAddress().setCity("New York");
System.out.printf("Person p1 = %s%n", p1);
System.out.printf("Person p2 = %s%n", p2);
}
 
/**
* Makes a deep copy of any Java object that is passed.
*/
private static Object deepCopy(Object object) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream);
outputStrm.writeObject(object);
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
ObjectInputStream objInputStream = new ObjectInputStream(inputStream);
return objInputStream.readObject();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static class Address implements Serializable, Cloneable {
 
private static final long serialVersionUID = -7073778041809445593L;
 
private String street;
private String city;
private String state;
private String postalCode;
public String getStreet() {
return street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public String getPostalCode() {
return postalCode;
}
@Override
public String toString() {
return "[street=" + street + ", city=" + city + ", state=" + state + ", code=" + postalCode + "]";
}
public Address(String s, String c, String st, String p) {
street = s;
city = c;
state = st;
postalCode = p;
}
// Copy constructor
public Address(Address add) {
street = add.street;
city = add.city;
state = add.state;
postalCode = add.postalCode;
}
// Support Cloneable
@Override
public Object clone() {
return new Address(this);
}
}
public static class Person implements Serializable, Cloneable {
private static final long serialVersionUID = -521810583786595050L;
private String firstName;
private String lastName;
private Address address;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Address getAddress() {
return address;
}
 
@Override
public String toString() {
return "[first name=" + firstName + ", last name=" + lastName + ", address=" + address + "]";
}
 
public Person(String fn, String ln, Address add) {
firstName = fn;
lastName = ln;
address = add;
}
// Copy Constructor
public Person(Person person) {
firstName = person.firstName;
lastName = person.lastName;
address = new Address(person.address); // Invoke copy constructor of mutable sub-objects.
}
// Support Cloneable
@Override
public Object clone() {
return new Person(this);
}
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Demonstrate shallow copy. Both are the same object.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Set city on person 2. City on both objects is changed.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=New York, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=New York, state=NY, code=010101]]
 
Demonstrate copy constructor. Object p2 is a deep copy of p1.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Set city on person 2. City on objects is different.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=New York, state=NY, code=010101]]
 
Demonstrate serialization. Object p2 is a deep copy of p1.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Set city on person 2. City on objects is different.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=New York, state=NY, code=010101]]
 
Demonstrate cloning. Object p2 is a deep copy of p1.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Set city on person 2. City on objects is different.
Person p1 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=Metropolis, state=NY, code=010101]]
Person p2 = [first name=Clark, last name=Kent, address=[street=1 World Center, city=New York, state=NY, code=010101]]
</pre>
 
=={{header|JavaScript}}==
You can use JSON for ordinary objects.
<syntaxhighlight lang="javascript">
<lang JavaScript>
var deepcopy = function(o){
return JSON.parse(JSON.stringify(src));
Line 578 ⟶ 1,425:
var dst = deepcopy(src);
print(JSON.stringify(src));
</syntaxhighlight>
</lang>
You can go further if you have <code>uneval()</code>. You can even deep copy objects with cyclic references.
<syntaxhighlight lang="javascript">
<lang JavaScript>
var deepcopy = function(o){
return eval(uneval(o));
Line 589 ⟶ 1,436:
var dst = deepcopy(src);
print(uneval(src));
</syntaxhighlight>
</lang>
 
=={{header|jq}}==
The distinction between "deep" and "shallow" copying is as irrelevant in a jq program as in elementary arithmetic. There is only one "equality" operator in jq and it is defined in terms of equality of values.
Line 608 ⟶ 1,456:
 
merely emits [[1,2], 2].
 
=={{header|Julia}}==
<syntaxhighlight lang="julia"># v0.6.0
 
cp = deepcopy(obj)</syntaxhighlight>
 
=={{header|Kotlin}}==
The JDK has an Object.clone() method but it only produces a 'shallow' copy.
 
If a 'deep' copy is needed, then usually a custom method would be written.
 
However, an easy way to produce a deep copy for any object, including one which contains cyclic or null references, is to serialize it to memory and then deserialize it back to a new object. A drawback is that the class of the object to be serialized needs to be marked as implementing the Serializable interface (albeit it contains no members).
 
The serialization approach is used below.
<syntaxhighlight lang="scala">// Version 1.2.31
 
import java.io.Serializable
import java.io.ByteArrayOutputStream
import java.io.ByteArrayInputStream
import java.io.ObjectOutputStream
import java.io.ObjectInputStream
 
fun <T : Serializable> deepCopy(obj: T?): T? {
if (obj == null) return null
val baos = ByteArrayOutputStream()
val oos = ObjectOutputStream(baos)
oos.writeObject(obj)
oos.close()
val bais = ByteArrayInputStream(baos.toByteArray())
val ois = ObjectInputStream(bais)
@Suppress("unchecked_cast")
return ois.readObject() as T
}
 
class Person(
val name: String,
var age: Int,
val sex: Char,
var income: Double,
var partner: Person?
) : Serializable
 
fun printDetails(p1: Person, p2: Person?, p3: Person, p4: Person?) {
with (p3) {
println("Name : $name")
println("Age : $age")
println("Sex : $sex")
println("Income : $income")
if (p4 == null) {
println("Partner : None")
}
else {
println("Partner :-")
with (p4) {
println(" Name : $name")
println(" Age : $age")
println(" Sex : $sex")
println(" Income : $income")
}
}
println("\nSame person as original '$name' == ${p1 === p3}")
if (p4 != null) {
println("Same person as original '${p2!!.name}' == ${p2 === p4}")
}
}
println()
}
 
fun main(args: Array<String>) {
var p1 = Person("John", 35, 'M', 50000.0, null)
val p2 = Person("Jane", 32, 'F', 25000.0, p1)
p1.partner = p2
var p3 = deepCopy(p1)
val p4 = p3!!.partner
printDetails(p1, p2, p3, p4)
 
println("..or, say, after 2 years have elapsed:-\n")
with (p1) {
age = 37
income = 55000.0
partner = null
}
p3 = deepCopy(p1)
printDetails(p1, null, p3!!, null)
}</syntaxhighlight>
 
{{out}}
<pre>
Name : John
Age : 35
Sex : M
Income : 50000.0
Partner :-
Name : Jane
Age : 32
Sex : F
Income : 25000.0
 
Same person as original 'John' == false
Same person as original 'Jane' == false
 
..or, say, after 2 years have elapsed:-
 
Name : John
Age : 37
Sex : M
Income : 55000.0
Partner : None
 
Same person as original 'John' == false
</pre>
 
=={{header|Lasso}}==
Every Lasso type has an ascopy and ascopydeep method.
 
<langsyntaxhighlight Lassolang="lasso">local(copy) = #myobject->ascopydeep</langsyntaxhighlight>
 
=={{header|Lingo}}==
<langsyntaxhighlight lang="lingo">-- supportsSupports lists, property lists, images, script instances and scalar values (integer, float, string, symbol).
on deepcopy (var, cycleCheck)
case ilk(var) of
#list, #propList, #image:
return var.duplicate()
#instance:
if string(var) starts "<Xtra " then return var -- deep copy makes no sense for Xtra instances
if voidP(cycleCheck) then cycleCheck = [:]
if not voidP(cycleCheck[var]) then return cycleCheck[var]
copy = var.script.rawNew()
cycleCheck[var] = copy
repeat with i = 1 to var.count
copy.setProp(var.getPropAt(i), deepcopy(var[i], cycleCheck))
end repeat
return copy
Line 629 ⟶ 1,592:
return var
end case
end</langsyntaxhighlight>
<syntaxhighlight lang="lingo">val = [#foo:42, "bar":[1,2,3, "Hello world!"]]
put deepcopy(val)
-- [#foo: 42, "bar": [1, 2, 3, "Hello world!"]]
 
val = script("MyClass").new()
val.foo = 42
val.bar = [1, 2, 3, "Hello world!"]]
copy = deepcopy(val)</syntaxhighlight>
 
=={{header|Lua}}==
Line 638 ⟶ 1,609:
===Recursive===
 
<langsyntaxhighlight Lualang="lua">function _deepcopy(o, tables)
if type(o) ~= 'table' then
Line 662 ⟶ 1,633:
function deepcopy(o)
return _deepcopy(o, {})
end</langsyntaxhighlight>
 
{{out}}
Line 729 ⟶ 1,700:
====Breadth-first====
 
<langsyntaxhighlight Lualang="lua">function deepcopy(o, mode)
 
if type(o) ~= 'table' then
Line 766 ⟶ 1,737:
 
return new_t
end</langsyntaxhighlight>
 
<pre>> q = {}
Line 796 ⟶ 1,767:
is copied. Then, the context is restored and copying of the parent table continues.
 
<langsyntaxhighlight Lualang="lua">function deepcopy(o, mode)
 
if type(o) ~= 'table' then
Line 885 ⟶ 1,856:
 
return tables[o] -- return the copy corresponding to the root table `o`
end</langsyntaxhighlight>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Everything in Mathematica is a value type.
<langsyntaxhighlight Mathematicalang="mathematica">a = {"foo", \[Pi], {<|
"deep" -> {# +
1 &, {{"Mathematica"}, {{"is"}, {"a"}}, {{{"cool"}}}, \
Line 897 ⟶ 1,868:
a[[3, 1, 1, 1]] = #^2 &;
Print[a];
Print[b];</langsyntaxhighlight>
{{out}}
<pre>{foo, -3 + π, {<|deep -> {#1^2 &, {{Mathematica}, {{is}, {a}}, {{{cool}}}, {{programming}, {language!}}}}|>}}
Line 903 ⟶ 1,874:
 
=={{header|Nim}}==
Works with Nim 01.94.50:
<syntaxhighlight lang ="nim">deepCopy(newObj, obj)</langsyntaxhighlight>
For example with binary trees:
<syntaxhighlight lang="nim">type
<lang nim>import queues, sequtils
 
type
Node[T] = ref TNode[T]
TNode[T] = object
Line 941 ⟶ 1,910:
 
echo "Tree:"
echo preorder tree</langsyntaxhighlight>
Output:
<pre>Tree2:
Line 952 ⟶ 1,921:
This code is just provided in order to achieve this task, but an OCaml programmer wouldn't use this kind of code, because this <code>copy</code> function is made generic due to the use of the [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Obj.html <code>Obj</code>] module, and it is not recommanded to use it.
 
<langsyntaxhighlight lang="ocaml">let rec copy t =
if Obj.is_int t then t else
let tag = Obj.tag t in
Line 967 ⟶ 1,936:
end else failwith "copy" ;;
 
let copy (v : 'a) : 'a = Obj.obj (copy (Obj.repr v))</langsyntaxhighlight>
 
OCaml programmers will prefer to use specialised copy functions for each mutable types. For base types like strings and arrays, the standard library provides copy functions: <code>String.copy</code> and <code>Array.copy</code>. For mutable user-defined data structures, we will create a copy function based on these previous copy functions. For example in the module [http://caml.inria.fr/pub/docs/manual-ocaml/libref/Hashtbl.html <code>Hashtbl</code>], the type is a record containing an integer and an array, so the copy function is defined as below:
<langsyntaxhighlight lang="ocaml">let copy h =
{ size = h.size;
data = Array.copy h.data }</langsyntaxhighlight>
 
=={{header|OxygenBasic}}==
<syntaxhighlight lang="text">
'DEEP COPY FOR A RECURSIVE TREE STRUCTURE
 
uses console
 
class branches
'
static int count
int level
int a,b,c
branches*branch1
branches*branch2
'
method constructor(int n)
=========================
level=n
count++
output count tab level cr
if level>0
new branches n1(n-1)
new branches n2(n-1)
@branch1=@n1
@branch2=@n2
endif
...
end method
'
method destructor
=================
if level>0
del branch1
del branch2
endif
...
end method
'
method RecurseCopy(int n, branches *dc, *sc)
============================================
dc.level=sc.level
dc.a=sc.a
dc.b=sc.b
dc.c=sc.c
if n>0
RecurseCopy n-1, byval @dc.branch1, byval @sc.branch1
RecurseCopy n-1, byval @dc.branch2, byval @sc.branch2
endif
end method
'
method DeepCopy() as branches*
==============================
new branches dc(level)
RecurseCopy level,dc,this
return @dc
end method
'
end class
 
output "count" tab "level" tab "(original)" cr
new branches br(3)
output "count" tab "level" tab "(copy)" cr
branches *bc = br.DeepCopy
pause
del bc
del br
</syntaxhighlight>
 
 
=={{header|PARI/GP}}==
Line 979 ⟶ 2,016:
In PARI, this is accomplished with the command <code>gcopy</code> rather than <code>shallowcopy</code> or <code>leafcopy</code>. The function takes and returns a <code>GEN</code>. See section 10.6 of the [http://pari.math.u-bordeaux.fr/pub/pari/manuals/2.5.0/libpari.pdf User's Guide to the PARI Library].
 
=={{Headerheader|Perl}}==
 
use [http://search.cpan.org/perldoc?Storable Storable]; <code>Storable::dclone()</code> is exactly what you are looking for.
 
<syntaxhighlight lang="perl">
<lang Perl>
#!/usr/bin/perl
use strict;
Line 995 ⟶ 2,032:
print Dumper($src);
print Dumper($dst);
</syntaxhighlight>
</lang>
 
=={{Header|Perl 6}}==
 
Perl 6 doesn't currently provide a proper mechanism for deep copies, but depending on your requirements you could use one of these work-arounds:
 
<br>
'''1) Use <code>.deepmap(*.clone)</code>:'''
 
<tt>.deepmap</tt> constructs a copy of the data structure, and <tt>.clone</tt> makes a shallow copy of each leaf node. Limitations:
* Hangs indefinitely when given a self-referential data structure.
* Descends only into <tt>Iterable</tt> collections (like <tt>Array</tt>/<tt>Hash</tt>), which means that a <tt>Pair</tt> or a typical custom object would be considered a leaf node.
 
<lang perl6>my %x = foo => 0, bar => [0, 1];
my %y = %x.deepmap(*.clone);
 
%x<bar>[1]++;
say %x;
say %y;</lang>
 
=={{header|Phix}}==
{{libheader|Phix/basics}}
Handled natively. Phix uses reference counting with copy-on-write semantics; the initial copy is fast even for huge complex and deeply nested structures (copying a single machine-word-sized reference and incrementing a single machine-word-sized reference count), and when a shared object (anything with a refcount>1) is modified, an internal clone of the minimum necessary levels occurs, with all the rest of the structure remaining shared, but obviously still properly protected in the same way.
<!--<syntaxhighlight lang="phix">-->
<span style="color: #004080;">object</span> <span style="color: #000000;">a<span style="color: #0000FF;">,</span> <span style="color: #000000;">b</span>
<span style="color: #000000;">a</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">2<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #008000;">"four"<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">5.6<span style="color: #0000FF;">,<span style="color: #000000;">7<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #000000;">8.9<span style="color: #0000FF;">}<span style="color: #0000FF;">}<span style="color: #0000FF;">}</span>
<span style="color: #000000;">b</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">a</span>
<span style="color: #000000;">b<span style="color: #0000FF;">[<span style="color: #000000;">3<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">4</span>
<span style="color: #0000FF;">?<span style="color: #000000;">a</span>
<span style="color: #0000FF;">?<span style="color: #000000;">b
<!--</syntaxhighlight>-->
{{out}}
<pre>
{1,{2,3},"four",{5.6,7,{8.9}}}
{bar => [0 2], foo => 0}
{1,{2,3},4,{5.6,7,{8.9}}}
{bar => [0 1], foo => 0}
</pre>
It is worth noting that this mechanism is also used for parameter passing, and when a local variable is both passed as a parameter and assigned on return, automatic pass-by-reference handling kicks in to avoid any unnecessary internal cloning.
 
However, JavaScript has pass-by-sharing semantics, and since 1.0.0 when pwa/p2js (the Phix to JavaScript transpiler) was introduced, a simple "with js" (which works identically to "with javascript_semantics") effectively disables '''both''' underlying semantic mechanisms simultaneously, and causes desktop/Phix to raise fatal runtime errors ("p2js violation: relies on copy on write semantics") indicating where a deep_copy() is needed, which is now a builtin (see builtins\repeat.e for the actual) and is a bit like this:
<br>
<!--<syntaxhighlight lang="phix">-->
'''2) Use <code>.perl.EVAL</code>:'''
<span style="color: #008080;">function</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #004080;">object</span> <span style="color: #000000;">o<span style="color: #0000FF;">)</span>
 
<span style="color: #004080;">object</span> <span style="color: #000000;">res</span>
<tt>.perl</tt> serializes the data structure to Perl 6 code, and <tt>.EVAL</tt> deserializes it. Limitations:
<span style="color: #008080;">if</span> <span style="color: #004080;">atom<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
* Doesn't work correctly if the data structure contains elements that can't be properly serialized, such as closures or file handles.
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">o</span>
 
<span style="color: #008080;">else</span>
<lang perl6>use MONKEY-SEE-NO-EVAL;
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat<span style="color: #0000FF;">(<span style="color: #008000;">' '<span style="color: #0000FF;">,<span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
 
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
my %x = foo => 0, bar => [0, 1];
<span style="color: #000000;">res<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #000000;">o<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]<span style="color: #0000FF;">)</span>
my %y = %x.perl.EVAL;
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
 
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
%x<bar>[1]++;
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
say %x;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
say %y;</lang>
<span style="color: #004080;">object</span> <span style="color: #000000;">c</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deep_copy<span style="color: #0000FF;">(<span style="color: #000000;">b<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?<span style="color: #000000;">c
<!--</syntaxhighlight>-->
It is worth pointing out that "with js" and deep_copy() have proved ''staggeringly'' effective and nowhere near as painful as first feared. In just a few months (1.0.0 was released in July 2021) I have tested, fixed where necessary, and marked as javascript compatible ''[https://www.rosettacode.org/mw/index.php?title=Special%3ASearch&search=phixonline some 450 rosettacode entries]'' for Phix, and only ''[https://www.rosettacode.org/mw/index.php?title=Special%3ASearch&search=notonline one tenth]'' of that as incompatible.
 
Or you ''could'' just serialize and deserialize, though it would probably be quite a bit slower:
<!--<syntaxhighlight lang="phix">-->
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins<span style="color: #0000FF;">\<span style="color: #000000;">serialize<span style="color: #0000FF;">.<span style="color: #000000;">e</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">d</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">deserialize<span style="color: #0000FF;">(<span style="color: #000000;">serialize<span style="color: #0000FF;">(<span style="color: #000000;">a<span style="color: #0000FF;">)<span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?<span style="color: #000000;">d
<!--</syntaxhighlight>-->
{{out}}
<pre>
{1,{2,3},4,{5.6,7,{8.9}}}
{bar => [0 2], foo => 0}
{1,{2,3},"four",{5.6,7,{8.9}}}
{bar => [0 1], foo => 0}
</pre>
 
=={{Headerheader|PHP}}==
 
PHP provides the <code>clone</code> operator ([http://www.php.net/manual/en/language.oop5.cloning.php docs]) for shallow copying, and allows you to hook into a magic class method called <code>__clone()</code> in your classes to do some of the lifting to create deeper copies, but this method won't create a true deep copy if you don't write the code to manage it in each of the child classes.
 
<langsyntaxhighlight PHPlang="php"><?php
class Foo
{
Line 1,066 ⟶ 2,108:
echo "Object contains {$object->some_value}, child contains {$object->child->some_value}\n",
"Clone of object contains {$deepcopy->some_value}, child contains {$deepcopy->child->some_value}\n";
?></langsyntaxhighlight>
 
 
Automatically generated deep copies can be created in any situation where your object graph can be serialized (i.e. does not contain any Closures or resources like DB connections or file handles):
 
<langsyntaxhighlight PHPlang="php"><?php
 
// stdClass is a default PHP object
Line 1,084 ⟶ 2,126:
 
echo "Object contains {$object->some_value}, child contains {$object->child->some_value}\n",
"Clone of object contains {$deepcopy->some_value}, child contains {$deepcopy->child->some_value}\n";</langsyntaxhighlight>
 
=={{header|PicoLisp}}==
Line 1,090 ⟶ 2,132:
 
For a known depth, it might be used in combination with other list functions. For example, to copy a non-cyclic structure of depth 2 with '[http://software-lab.de/doc/refM.html#mapcar mapcar]':
<syntaxhighlight lang PicoLisp="picolisp">(mapcar copy List)</langsyntaxhighlight>
Copying non-cyclic structures of arbitrary depth and list-termination could be handled with a custom function (using '[http://software-lab.de/doc/refC.html#cons cons]'):
<langsyntaxhighlight PicoLisplang="picolisp">(de deepCopy (X)
(if (atom X)
X
(cons (deepCopy (car X)) (deepCopy (cdr X))) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (setq A '((a . b) (c d e) f g . e))
-> ((a . b) (c d e) f g . e)
 
Line 1,121 ⟶ 2,163:
 
: (== (cadr A) (cadr B))
-> NIL # The same holds for sub-structures</langsyntaxhighlight>
For cyclic structures, the above 'deepCopy' function could be extended, to remember already visited structures and their copies in a mark list:
<langsyntaxhighlight PicoLisplang="picolisp">(de deepCopy (X)
(let Mark NIL
(recur (X)
Line 1,133 ⟶ 2,175:
(push 'Mark (cons X @))
(set @ (recurse (car X)))
(con @ (recurse (cdr X))) ) ) ) ) ) )</langsyntaxhighlight>
Test:
<langsyntaxhighlight PicoLisplang="picolisp">: (setq A '(a b .) B (deepCopy A))
-> (a b .)
: A
Line 1,146 ⟶ 2,188:
 
: (== A B)
-> NIL # but they are not identical (pointer-equal)</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<syntaxhighlight lang="purebasic">Macro PrintStruc(StrucVal)
PrintN(Str(StrucVal#\value1))
PrintN(Chr(StrucVal#\value2))
PrintN(StrucVal#\value3)
If StrucVal#\value4
PrintN("TRUE")
Else
PrintN("FALSE")
EndIf
PrintN("")
EndMacro
 
Structure TTypeA
value1.i
value2.c
value3.s[10]
value4.b
EndStructure
 
Define.TTypeA a, b
 
a\value1=10
a\value2='A'
a\value3="OK"
a\value4=#True
 
b=a
 
a\value1=20
a\value2='B'
a\value3="NOK"
a\value4=#False
 
If OpenConsole("")
PrintN("Value of 'a':") : PrintStruc(a)
PrintN("Value of 'b':") : PrintStruc(b)
Input()
EndIf</syntaxhighlight>
{{out}}<pre>Value of 'a':
20
B
NOK
FALSE
 
Value of 'b':
10
A
OK
TRUE
</pre>
 
=={{header|Python}}==
<langsyntaxhighlight Pythonlang="python">import copy
deepcopy_of_obj = copy.deepcopy(obj)</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 1,160 ⟶ 2,254:
to get a new copy:
 
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
 
Line 1,175 ⟶ 2,269:
(printf "both: ~s\n" (list x (deepcopy x)))))
(try (shared ([x (cons 1 x)]) (list x x)))
</syntaxhighlight>
</lang>
 
Output:
Line 1,182 ⟶ 2,276:
deepcopy: (#0=(1 . #0#) #0#)
both: ((#0=(1 . #0#) #0#) (#1=(1 . #1#) #1#))
</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
 
Raku doesn't currently provide a proper mechanism for deep copies, but depending on your requirements you could use one of these work-arounds:
 
<br>
'''1) Use <code>.deepmap(*.clone)</code>:'''
 
<tt>.deepmap</tt> constructs a copy of the data structure, and <tt>.clone</tt> makes a shallow copy of each leaf node. Limitations:
* Hangs indefinitely when given a self-referential data structure.
* Descends only into <tt>Iterable</tt> collections (like <tt>Array</tt>/<tt>Hash</tt>), which means that a <tt>Pair</tt> or a typical custom object would be considered a leaf node.
 
<syntaxhighlight lang="raku" line>my %x = foo => 0, bar => [0, 1];
my %y = %x.deepmap(*.clone);
 
%x<bar>[1]++;
say %x;
say %y;</syntaxhighlight>
 
{{out}}
<pre>
{bar => [0 2], foo => 0}
{bar => [0 1], foo => 0}
</pre>
 
<br>
'''2) Use <code>.raku.EVAL</code>:'''
 
<tt>.raku</tt> serializes the data structure to Raku code, and <tt>.EVAL</tt> deserializes it. Limitations:
* Doesn't work correctly if the data structure contains elements that can't be properly serialized, such as closures or file handles.
 
<syntaxhighlight lang="raku" line>my %x = foo => 0, bar => [0, 1];
my %y = %x.raku.EVAL;
 
%x<bar>[1]++;
say %x;
say %y;</syntaxhighlight>
 
{{out}}
<pre>
{bar => [0 2], foo => 0}
{bar => [0 1], foo => 0}
</pre>
 
Line 1,187 ⟶ 2,325:
Rubyists can hack a deep copy by using the core class Marshal. The intermediate form of <code>Marshal.load(Marshal.dump object)</code> saves the object and any descendant objects.
 
<langsyntaxhighlight lang="ruby"># _orig_ is a Hash that contains an Array.
orig = { :num => 1, :ary => [2, 3] }
orig[:cycle] = orig # _orig_ also contains itself.
Line 1,208 ⟶ 2,346:
p [(orig.equal? orig[:cycle]),
(copy.equal? copy[:cycle]),
(not orig.equal? copy)] # => [true, true, true]</langsyntaxhighlight>
 
Marshal cannot dump an object that relates to the system (like Dir or IO), relates to the program (like MatchData or Thread), uses an anonymous class or module, or has a singleton method. (<code>ri Marshal.dump</code> documents this restriction.) If Marshal encounters any such object, then the deep copy fails.
 
Marshal can dump internal objects, but never copies them. The internal objects are <code>nil</code>, <code>false</code>, <code>true</code> and instances of Fixnum or Symbol. For example, <code>Marshal.load(Marshal.dump :sym)</code> returns the original <code>:sym</code>, not a copy. <blockquote style="font-size: smaller;">The internal objects are almost immutable, so there is almost no reason to copy them. Yet, there are esoteric ways to modify them. For example, <code>nil.instance_eval { @i = 1 }</code> would modify <code>nil</code>. A program cannot have another copy of <code>nil</code> to escape such modification. If there was a deep copy of some object that contains <code>nil</code>, then such modification would also affect <code>nil</code> inside such copy.</blockquote>
 
=={{header|Rust}}==
This is what the <code>Clone</code> trait exists for although the depth of the copy is arbitrary and up to the type that implements the trait.
 
<syntaxhighlight lang="rust">// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone).
#[derive(Clone)]
struct Tree<T> {
left: Leaf<T>,
data: T,
right: Leaf<T>,
}
 
type Leaf<T> = Option<Box<Tree<T>>>;
 
impl<T> Tree<T> {
fn root(data: T) -> Self {
Self { left: None, data, right: None }
}
 
fn leaf(d: T) -> Leaf<T> {
Some(Box::new(Self::root(d)))
}
}
 
fn main() {
let mut tree = Tree::root([4, 5, 6]);
tree.right = Tree::leaf([1, 2, 3]);
tree.left = Tree::leaf([7, 8, 9]);
 
let newtree = tree.clone();
}</syntaxhighlight>
 
=={{header|Scheme}}==
<syntaxhighlight lang="scheme">
(define (deep-copy-1 exp)
;; basic version that copies an arbitrary tree made up of pairs
(cond ((pair? exp)
(cons (deep-copy-1 (car exp))
(deep-copy-1 (cdr exp))))
;; cases for extra container data types can be
;; added here, like vectors and so on
(else ;; atomic objects
(if (string? exp)
(string-copy exp)
exp))))
 
(define (deep-copy-2 exp)
(let ((sharing (make-hash-table)))
(let loop ((exp exp))
(cond ((pair? exp)
(cond ((get-hash-table sharing exp #f)
=> (lambda (copy)
copy))
(else
(let ((res (cons #f #f)))
(put-hash-table! sharing exp res)
(set-car! res (loop (car exp)))
(set-cdr! res (loop (cdr exp)))
res))))
(else
(if (string? exp)
(string-copy exp)
exp))))))
 
(define t1 '(a b c d))
(define t2 (list #f))
(set-car! t2 t2)
(define t2b (list #f))
(set-car! t2b t2b)
(define t3 (list #f #f))
(set-car! t3 t3)
(set-car! (cdr t3) t3)
(define t4 (list t2 t2b))
 
;> (print-graph #t)
;> (deep-copy-2 t1)
;(a b c d)
;> (deep-copy-2 t2)
;#0=(#0#)
;> (deep-copy-2 t3)
;#0=(#0# #0#)
;> (deep-copy-2 t4)
;(#0=(#0#) #1=(#1#))
</syntaxhighlight>
 
=={{header|Sidef}}==
''Object.dclone()'' returns a deep clone of any mutable object.
<langsyntaxhighlight lang="ruby">var src = Hash(foo => 0, bar => [0,1])
 
# Add a cyclic reference
Line 1,230 ⟶ 2,452:
# The address of dst
say dst.object_id
say dst{:baz}.object_id</langsyntaxhighlight>
{{out}}
<pre>
Line 1,241 ⟶ 2,463:
=={{header|Tcl}}==
Tcl uses an immutable value model that is implemented as copy-on-write at the low level, so deep copies are generally not required. However, they can be achieved by simply appending a letter to the value and stripping it off again:
<langsyntaxhighlight lang="tcl">set deepCopy [string range ${valueToCopy}x 0 end-1]</langsyntaxhighlight>
For objects (as introduced in Tcl 8.6), there is a command to create a copy:
<langsyntaxhighlight lang="tcl">set copiedObject [oo::copy $originalObject]</langsyntaxhighlight>
 
=={{header|Wren}}==
{{libheader|Wren-seq}}
{{libheader|Wren-trait}}
Wren does not have any built-in facilities for deep-copying an object and you therefore have to write your own method to do this.
 
However, using the above module, a class can inherit from the Cloneable or CloneableSeq abstract class and override its clone() method. Knowing that objects have such a method is useful when cloning other objects which contain them as fields or nested fields.
 
Note though that, since Wren is dynamically typed, it may be impractical or impossible to deep-copy generic objects because, if an object does not have a clone() method, all that can be done is to return the argument itself which, unless it is a built-in immutable type, will simply be a reference to the original.
 
In the following example, we attempt to deep-copy a custom type, MyMap, which wraps the built-in generic Map type. This succeeds here because of the types of values used but wouldn't succeed if a Map value were, say, some user-defined type which didn't have a clone() method.
<syntaxhighlight lang="wren">import "./trait" for Cloneable, CloneableSeq
import "./seq" for Lst
 
class MyMap is Cloneable {
construct new (m) {
if (m.type != Map) Fiber.abort("Argument must be a Map.")
_m = m
}
 
m { _m }
 
toString { _m.toString }
 
clone() {
// Map keys are always immutable built-in types so we only need to worry about
// their values which can be anything.
var m2 = {}
for (me in _m) {
var v = me.value
m2[me.key] = (v is List) ? Lst.clone(v) :
(v is Cloneable || v is CloneableSeq) ? v.clone() : v
}
return MyMap.new(m2)
}
}
 
var my = MyMap.new({"a": 0, "b": 1, "c": [2, 3], "d": MyMap.new({"e": 4})})
var my2 = my.clone()
System.print("Before any changes:")
System.print(" my = %(my)")
System.print(" my2 = %(my2)")
// now change my2
my2.m["a"] = 5
my2.m["b"] = 6
my2.m["c"][0] = 7
my2.m["c"][1] = 8
my2.m["d"].m["e"] = 9
my2.m["d"].m["f"] = 10
System.print("\nAfter changes to my2:")
System.print(" my = %(my)")
System.print(" my2 = %(my2)")</syntaxhighlight>
 
{{out}}
<pre>
Before any changes:
my = {c: [2, 3], d: {e: 4}, b: 1, a: 0}
my2 = {c: [2, 3], d: {e: 4}, b: 1, a: 0}
 
After changes to my2:
my = {c: [2, 3], d: {e: 4}, b: 1, a: 0}
my2 = {c: [7, 8], d: {e: 9, f: 10}, b: 6, a: 5}
</pre>
 
=={{header|Z80 Assembly}}==
There is no built-in type checking, so there's no way to tell apart pointers from actual data without knowing it in advance. Other than that, a deep copy is very easy to perform. A single byte or word can be copied by loading it from memory and writing it to a new location.
<syntaxhighlight lang="z80">LD HL,(&C000)
LD (&D000),HL</syntaxhighlight>
 
For copying a string or record, the <code>LDIR</code> command makes this very easy, provided you know the size (in bytes) of the data you wish to copy. Label arithmetic is the easiest way to do this for fixed-size data.
 
<syntaxhighlight lang="z80">LD HL,MyString
LD DE,UserRam
LD BC,MyString_End-MyString ;the difference between these two addresses is the byte count.
LDIR ;essentially C's memcpy()
 
MyString:
byte "Hello, world!",0
 
UserRam:
ds 32,0 ;32 bytes of memory initialized to zero.</syntaxhighlight>
 
 
 
{{omit from|Haskell}}
{{omit from|C|Deepcopy not very useful without runtime type info}}
{{omit from|GUISS}}
{{omit from|PureBasic}}
9,476

edits