What is Triat in Rust
Interface/class in Rust(declared with keyword trait) having Virtual Functions(not pure Virtual) declared or defined
inside it. These functions are implemented(overridden) on type.
Declaration & Definition
Trait is implemented for particular types. Eg: add_to_db() function is overridden for Employee, Contractor Type.
User Defined Triats
Trait Declaration
pub trait T {
// No need to add pub in front of function
// Trait methods are public by default
fn add(&self);
// Functions can be defined
// with default implementation
fn test(&self) {
println!("test()");
}
}
|
Type on which trait is defined
pub struct S {
pub x: i32,
pub y: i32,
}
|
Trait Definition
//impl triat for type
impl T for S {
fn add(&self) {
println!("Sum: {}", self.x + self.y);
}
}
fn main() {
let a = S {
x: 1,
y: 2,
};
a.add();
}
|
Passing trait as argument to function
// trait T defined above
pub fn fun(t: &impl T) {
t.test();
}
fn main() {
let a = S {
x: 1,
y: 2,
};
fun(&a);
}
$ cargo run
test()
Returning trait from function
// trait T defined above
// This function can return struct of type S also
pub fn ret_trait() -> impl T {
S {
x: 1,
y: 2,
}
}
Trait Bound
These are generic functions(templates) but must implement one or more traits,
which ensures that the type provides certain behavior or methods
// Trait(T) is defined above
//< type: TraitName> (var: type)
pub fn fun1 <t: T> (item: &t) {
item.test();
}
$ cargo run
test()
Using + //Friend Function
There can be a function which takes 2 or more traits(virtual function).
pub fn test <T: Trait1 + Trait2> (param: &T) {
OR
pub fn test (param: &(impl Trait1 + Trait2) {
Using where clause //Friend Function
pub fn test <T: Trait1 + Triat2, U: Triat2 + Triat2>(t: &T, u: &U) -> i32 {
OR
pub fn test <T, U>(t: &T, u: &U) -> i32
where T: Triat2 + Triat2
U: Triat2 + Triat3
{