Open In App

Rust – The #[derive] Attribute

Last Updated : 26 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In Rust, we come across the concept of the #[derive] attribute. Derive attribute is used for generating data structures automatically by using MetalistPaths syntax for specifying the traits that help in implementing paths to derive macros for processing. 

Expression of the trait is:

#[derive(PartialEq, Clone)]
struct Foo<T> {
   a: i32,
   b: T,
}
 

In this example, we are comparing a struct and printing a tuple. Here, we are comparing the traits Eq, PartialEq, and the PartialOrd trait.

Example 1:

Rust




// Rust program for The #[derive] attribute
// `GFGStruct`, a tuple struct that can be compared
  #[derive(PartialEq, PartialOrd)]
  struct GFGStruct(f64);
  
// `GFGTuple, a tuple struct that can be printed
  #[derive(Debug)]
  struct GFG(i32);
  
  impl GFG 
  {
    fn parameter_one(&self) -> GFGStruct 
    {
        let &GFG(variable) = self;
        GFGStruct(variable as f64 * 8.00)
    }
  }
  
fn main()  
  {
  
    let firstvariable = GFG(1);
    println!("Lets learn rust from {:?}", firstvariable);
  
    let secondvariable = GFGStruct(50.0);
  
    let thirdvariable =
        if firstvariable.parameter_one() < secondvariable 
     {
            "first variable"
     
     else 
     {
            "Second variable"
     };
  
    println!("{} gets printed on screen.", thirdvariable);
}


Output:

 

The #derive attribute can be explained using this example. We create a tuple known as GFGStruct and import the #derive(PartialEq, PartialOrd) attributes. GFGStruct is used for comparing and GFGTuple is created so that it can be printed. 

Next, we create an impl GFG where we pass a parameter named variable. This variable is passed on to the GFGStruct as a floating point variable. Now, we compare the first variable and the second variable that we had declared in the main function. In the variables, we pass a floating value and an integer value in the GFG impl. 

After passing, we compare the variables by declaring the third variable and we clearly see that 1<50. Therefore, we see that the third variable gets the value of the first variable as the first variable.parameter_one < second variable



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads