Learn More : The Book , Rust by Example , The Rust Reference , Rust Nomicon , Rust Design Patterns
In Rust, a supertrait is a trait that must be implemented for a type before another trait can be implemented for that type. It’s similar to saying that one trait is a prerequisite for another
Syntax: trait SubTrait: SuperTrait {}.
A Trait can inherit other traits method see std::fmt::Display as example.
This is the Closest thing in OOP
The fmt::Display trait requires you to implement one method: fmt. This method is used to format a value using a formatter. The to_string() method is not directly defined in fmt::Display, but it is automatically available for any type that implements fmt::Display because Rust provides a default implementation of to_string() for any type that implements fmt::Display
pub trait Display {
// Required method
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>;
}
main.rs
use std::fmt;
trait OutlinePrint: fmt::Display {
fn outline_print(&self) {
let output = self.to_string();
let len = output.len();
println!("{}", "*".repeat(len + 4));
println!("*{}*", " ".repeat(len + 2));
println!("* {} *", output);
println!("*{}*", " ".repeat(len + 2));
println!("{}", "*".repeat(len + 4));
}
}
struct Point {
x: i32,
y: i32,
}
impl OutlinePrint for Point {}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let p = Point{x:1,y:2};
p.outline_print();
}