Deepcopy: Difference between revisions

(→‎{{header|Rust}}: Added Rust)
Line 1,225:
 
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.
 
<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(d: T) -> Self {
Tree { left: None, data: d, right: None }
}
fn leaf(d: T) -> Leaf<T> {
Some(Box::new(Tree::root(d)))
}
}
 
 
fn main() {
let mut tree = Tree::root(vec![4,5,6]);
tree.right = Tree::leaf(vec![1,2,3]);
tree.left = Tree::leaf(vec![7,8,9]);
let newtree = tree.clone();
}</lang>
 
=={{header|Sidef}}==