Open In App

Rust – Clone Trait

Last Updated : 12 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we have a concept of clone trait. Clone traits have the ability to duplicate objects explicitly. We can make anything copy with the Clone Trait.

Syntax:

//pub refers to public trait

pub trait Clone {
   fn clone(&self) -> Self;

   fn clone_from_trait(&mut self, source: &Self) { … }
}

In Rust, we have various Types that can be implemented via Clone Trait. While dealing with available resources, Rust’s default behavior is transferring them during the assignment operator or when we call functions. The clone trait helps us in making the copy of resources by the usage of the .clone() trait.

T: Copy
a:T
b: &T
let a = b.clone'()

This expression implies a=*b and is an expression of implementing a Function Pointer using Clone Trait.

Example 1:

Rust




//Program for Rust - Clone Trait
#[derive(Debug, Clone, Copy)]
struct GeeksforGeeks;
struct PairwiseElements(Box<i32>, Box<i32>,Box<i32>);
 
fn main() {
     
  // Instantiating GFG
    let gfg = GeeksforGeeks;
    let _copied_unit = gfg;
    let pairwise = Pairwise(Box::new(10), Box::new(20),Box::new(30));
    println!("original elements: {:?}", pairwise);
    let moved_pair = pairwise;
    println!("moved elements: {:?}", moved_pair);
 
    let cloned_pair = moved_pair.clone();
    drop(moved_pair);
    println!("cloned elements: {:?}", cloned_pair);
}


Output:

 

Explanation: 

In this example, we have declared a struct GeeksforGeeks and imported the struct #derive{(Debug, Clone, Copy)] and then we define this struct without any resources. Next, we define a tuple struct PairwiseElements that takes 3 parameters with i32 parameters. Inside the main function, we instantiate gfg with GeeksforGeeks. Also, we have used a variable (_copied_unit) with no resources.

Next, we instantiate pairwise with PairwiseElements with three values (10,20,30) and then print the original elements with original elements. Once, we use the moved_pair to resources, the resources are also transferred as well. and Thus printing now yields the same results.

Now, we can use the .clone() using the clone trait that yields the same result without the need for copying or moving as seen in the 3rd output where (10,20,30) are printed.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads