Deepcopy: Difference between revisions

Content added Content deleted
(Removing omission from C after adding implementation.)
Line 1,525: Line 1,525:
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.
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).
<lang rust>// The compiler can automatically implement Clone on structs (assuming all members have implemented Clone).
#[derive(Clone)]
#[derive(Clone)]
struct Tree<T> {
struct Tree<T> {
Line 1,536: Line 1,536:


impl<T> Tree<T> {
impl<T> Tree<T> {
fn root(d: T) -> Self {
fn root(data: T) -> Self {
Tree { left: None, data: d, right: None }
Self { left: None, data, right: None }
}
}

fn leaf(d: T) -> Leaf<T> {
fn leaf(d: T) -> Leaf<T> {
Some(Box::new(Tree::root(d)))
Some(Box::new(Self::root(d)))
}
}
}
}



fn main() {
fn main() {
let mut tree = Tree::root(vec![4,5,6]);
let mut tree = Tree::root([4, 5, 6]);
tree.right = Tree::leaf(vec![1,2,3]);
tree.right = Tree::leaf([1, 2, 3]);
tree.left = Tree::leaf(vec![7,8,9]);
tree.left = Tree::leaf([7, 8, 9]);

let newtree = tree.clone();
let newtree = tree.clone();
}</lang>
}</lang>