Thursday, May 6, 2021

Inheritance in Rust

Inheritance is a mechanism whereby an object can inherit from another object’s definition, thus gaining the parent object’s data and behavior without you having to define them again. 

In Rust, there is no concept of "inheriting" the properties of a struct. Instead, when you are designing the relationship between objects do it in a way that one's functionality is defined by an interface (a trait in Rust).


Traits Inheritance example


trait Cat {
    fn get_sound(&self) -> String;
}

// CatPersia inherits from Cat trait
trait CatPersia : Cat { 
  fn number_of_feet(&self) -> i32;
}

// CatSphynx inherits from CatPersia and Cat traits
trait CatSphynx : CatPersia + Cat { 
  fn number_of_tail(&self) -> i32;
}




Let's see another example code below


trait A {
    fn shown_a(&self);
}

//B inherits from A trait
trait B: A {        
    fn shown_b(&self);
}

//C inherits from A and B traits
trait C: A + B {    
    fn shown_c(&self);
}

struct D {}

impl A for D {
    fn shown_a(&self) {
        println!("Implement A");
    }
}

impl B for D {
    fn shown_b(&self) {
        println!("Implement B");
    }
}

impl C for D {
    fn shown_c(&self) {
        println!("Implement C");
    }
}

fn main() {
    let d = D {};
    d.shown_a();
    d.shown_b();
    d.shown_c();
}



Result shown as below:



Thank you




No comments:

Post a Comment