Clone. 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.
Part 1 To have access to a clone() method on a struct, we can derive the Clone trait. Many standard types (like String) already have this trait.
Part 2 We create an instance of the struct. This struct has a clear owner (the main method).
Part 3 We want to place the Data struct within 10 elements of a vector, so we use clone() and pass the clone to the Vector push method.
Part 5 The 2 vectors can be read in similar ways—the Arcs do not change how we access the inner HashSet.
Part 6 If we need to mutate the structs within the 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.