The clone()
method in Rust is available when the Clone trait is implemented on a struct
. It allows us to easily create new instances of the struct
—and each one can have a different owner.
With clone we copy the entire struct
, and this can cause a slowdown. But by placing the struct
within an Arc
(or Rc
) we can copy just the bytes of the reference.
This program uses clone()
to place a struct
within many elements of a vector. It does this first by cloning the entire struct
, and then by cloning just an Arc
.
clone()
method on a struct
, we can derive the Clone trait. Many standard types (like String
) already have this trait.struct
. This struct
has a clear owner (the main method).struct
within 10 elements of a vector, so we use clone()
and pass the clone to the Vector
push method.Arc
for the struct
, and then clone that into the Vector
. This is faster as less copying is done.HashSet
.Vector
, we must have the original structs, as Arcs prevent mutation.use std::collections::HashSet; use std::sync::Arc; // Part 1: specify a struct that derives the Clone trait. #[derive(Clone)] struct Data { h: HashSet<usize>, } fn main() { // Part 2: create the struct. let d = Data { h: HashSet::from([0, 1, 2]), }; // Part 3: clone the entire struct into 10 elements of a vector. let mut v = vec![]; for _ in 0..10 { v.push(d.clone()); } // Part 4: place the struct into an Arc, then clone the arc. // ... Each arc is much smaller in size than the entire struct, so this is faster. let d_arc = Arc::new(d); let mut v_arc = vec![]; for _ in 0..10 { v_arc.push(d_arc.clone()); } // Part 5: the cloned structs or arcs to the struct can be read in the same way. println!("{}", v[5].h.contains(&2)); println!("{}", v_arc[5].h.contains(&2)); // Part 6: we can only modify the structs that were not placed in arcs. v[5].h.insert(3); }true true
In Rust we must have an established owner of each struct
instance. But with clone()
we can duplicate structs, allowing us to have many different owners of the data.