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