In this post we will be implementing Polymorphism in Rust.
But what is Polymorphism?
In simple terms, it is the ability to pass an argument that can be of different types, to a function with only one implementation, instead of separate ones for each different type.
Code: Online Demo Link
// Polymorphism in Rust
// Online Demo: https://repl.it/repls/PerfectSandybrownCarat
const PI: f64 = 3.1416;
struct Circle {
radius: f64
}
struct Rectangle {
height: f64,
width: f64
}
// Since both Circle and Rectangle are shapes,
// we can label common behavior in a `trait` type.
// A `trait` is basically a type that groups
// certain behaviors that are similar in meaning
// but can be different in implementation. e.g. a
// dog and a human, both can walk, but they walk
// differently. You can also think of traits as
// kind of similar to interfaces in other languages.
trait Shape {
fn area(&self) -> f64;
}
// Although both shapes have an area
// but their ways of calculating it
// are different. e.g. (dog human walking analogy)
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.radius * self.radius
}
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.height * self.width
}
}
// Here, we are saying, hey accept
// any type that implements a `trait`
// called Shape. e.g. any object that
// can walk (from dog human analogy).
fn print_area(shape: &dyn Shape) {
println!("{}", shape.area());
}
// Or we can also make a generic function.
// This is similar to `print_area` but may
// have the benifits of static type checking,
// since it's a generic, so two versions of the
// same function get generated with relevant
// absolute/concrete types. (not sure though)
fn print_area_generic<T: Shape> (shape: &T) {
println!("{}", shape.area());
}
fn main() {
let circle = Circle{radius: 2.0};
let rectangle = Rectangle{height: 3.0, width: 5.0};
print_area(&circle); // 12.5664
print_area(&rectangle); // 15
print_area_generic(&circle); // 12.5664
print_area_generic(&rectangle); // 15
}
I hope this has been interesting for you.
Take Care && Good Bye. 😊
Top comments (0)