Open In App

Rust – Supertraits

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

In Rust, we have a concept of super traits. Rust being a modern systems-based programming language focuses mainly on the speed, safe and concurrent aspects of programming.  

Supertraits in Rust are traits that require implementation for conversion of specific types for implementing specific traits. As in Rust, there is no concept of inheritance but a concept of one trait being a superset of another trait therefore generic or trait objects are bound by traits that have access to super trait items.

Syntax:

#![allow(unused)]
fn main() {
trait Courses { fn dsa(&self) -> f64; }

trait GFG : Courses {fn 
}
 

Example 1:

Rust




// Rust program for Supertraits
 
#[allow(dead_code)]
 trait GFG {
    fn name(&self) -> String;
}
 
// First trait
 trait Courses: GFG {
    fn coursename(&self) -> String;
}
 
// Second trait
 trait Hackathon {
    fn languagesallowed(&self) -> String;
}
 
 trait GeeksforgeeksWebsite: Hackathon + Courses {
    fn username(&self) -> String;
}
 
#[allow(dead_code)]
 fn gfg_website_greeting(activity: &dyn GeeksforgeeksWebsite) -> String {
     
     
     
    format!(
       "Name of GFG is {}. Course available are {}.
        languages allowed in the Hackathon are {}.
        User's name is {}",
        activity.name(),
        activity.coursename(),
        activity.languagesallowed(),
        activity.username()
    )
}
 
fn main()
{
}


Output:

 

Explanation:

Here, GFG is declared as a trait. GFG is the super trait of courses. Implementation of the GFG trait requires us to also impl the GFG trait. Along with that, we declare two more traits -> Courses and Hackathon (both are string types).  GeeksforgeeksWebsite is a subtrait of both Courses and Hackathons. To implement, GeeksforgeeksWebsite requires us to impl both the super traits.

We have used format! as the strings are interpolated and an incorrect trait implementation would return an error itself.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads