Open In App

Rust – Generic Traits

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

Rust is an extremely fast programming language that supports speed, concurrency, as well as multithreading. In Rust, we have a concept of Generic Traits where Generics are basically an abstraction of various properties, and Traits are basically used for combining generic types for constraining types for accepting particular behavior of various types.

Example 1:

Rust




// Rust code for generic traits
struct Empty;
struct Null;
  
trait GeeksforGeeks<T> {
    fn gfg_func(self, _: T);
}
  
impl<T, U> GeeksforGeeks<T> for U {
     
    fn gfg_func(self, _: T) {}
}
  
fn main() {
    let variable_one = Empty;
    let variable_two  = Null;
      
   variable_one.gfg_func(variable_two);
  
}


Output:

 

Explanation:

In this example, we declare two non-copyable structs Empty and Null. Then, we declare a trait GeeksforGeeks which is implemented over T, and then define a function gfg_func that takes a single parameter T and does not print or do anything.

Next, we implement the GeeksforGeeks<T> trait for the generic parameter T and caller U. Implementing this trait, takes ownership of both passed arguments and then we deallocate both. In the main function, we declare two variables named variable_one and variable two and then we assign the values of the struct Empty and Null respectively. Now, we deallocate the structs by passing them via gfg_func() [ gfg_func() takes self as a parameter and takes a Trait T].


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads