Wednesday, May 5, 2021

Polymorphism in Rust

Polymorphism is the ability of an object to take on many forms, the same function has a different implementation. Polymorphism is achieved by operator overloading (compile-time) and method overriding (run-time)Rust takes a different approach to achieve polymorphism by using trait.




pub trait Shape {
    fn area(&self) -> f32;
}

pub struct Rectangle {
    pub length: f32,
    pub width: f32,
}

impl Shape for Rectangle {
    fn area(&self) -> f32 {
        self.length * self.width
    }
}

pub struct Square {
    side: f32,
}

impl Shape for Square {
    fn area(&self) -> f32 {
        self.side * self.side
    }
}

fn main() {
    let rectangle = Rectangle {
        length: 20.50,
        width: 10.50,
    };
    println!("Area of Rectangle = {}", rectangle.area());
    let square = Square { side: 8.50 };
    println!("Area of Square = {}", square.area());
}



Result shown as below



Thank you



No comments:

Post a Comment