Polymorphism in Rust

Polymorphism is a programming technique that allows objects of different types to be treated as if they are of the same type. In Rust, polymorphism is primarily achieved through the use of traits and generics, rather than subtyping or inheritance, which are more common in object-oriented languages. While it is possible to emulate polymorphism using the Deref trait, this approach is not idiomatic in Rust and can lead to confusing code.

Polymorphism with Trait Objects

In Rust, a common and idiomatic way to achieve polymorphism is through the use of trait objects. A trait object is a way to call methods on a type that implements a particular trait without knowing the exact type at compile time. This is done by using a pointer, such as Box<dyn Trait>, to store the trait object.

Example: Using Trait Objects

Consider the following example where we define an Animal trait and implement it for Dog and Cat structs:

Listing 10.10 Emulating polymorphism with trait objects (good practice)

trait Animal {
    fn speak(&self) -> &str;
    fn name(&self) -> &str;
}

struct Dog {
    name: String,
}
impl Dog {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}
impl Animal for Dog {
    fn speak(&self) -> &str {
        "Woof!"
    }
    fn name(&self) -> &str {
        &self.name
    }
}

struct Cat {
    name: String,
}
impl Cat {
    fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
        }
    }
}
impl Animal for Cat {
    fn speak(&self) -> &str {
        "Meow!"
    }
    fn name(&self) -> &str {
        &self.name
    }
}

To test this implementation, we can create a vector of Box<dyn Animal> and call the speak() method on each Animal in the vector:

Listing 10.11 Testing the polymorphism with trait objects

fn main() {
    let dog = Box::new(Dog::new("Rusty"));
    let cat = Box::new(Cat::new("Misty"));

    let animals: Vec<Box<dyn Animal>> = vec![dog, cat];

    for animal in animals {
        println!("{} says {}", animal.name(), animal.speak());
    }
}

Emulating Polymorphism with Deref

While Rust's idiomatic approach to polymorphism is through traits, it is possible to emulate polymorphism using the Deref trait. This involves using Deref to allow method calls on a type as if it were another type, similar to subclassing in object-oriented languages. However, this approach is not recommended as it can lead to unclear and confusing code.

Example: Using Deref

In the following example, we create an Animal struct and treat it as a superclass of the Dog and Cat structs by returning the inner Animal with a Deref:

Listing 10.12 Emulating polymorphism with Deref (bad practice)

use std::ops::Deref;

struct Animal {
    name: String,
}
impl Animal {
    fn new(name: &str) -> Animal {
        Animal { name: name.to_string() }
    }
    fn name(&self) -> &str {
        &self.name
    }
}

struct Dog(Animal);
impl Dog {
    fn new(name: &str) -> Self {
        Self(Animal::new(name))
    }
    fn speak(&self) -> &str {
        "Woof!"
    }
}
impl Deref for Dog {
    type Target = Animal;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

struct Cat(Animal);
impl Cat {
    fn new(name: &str) -> Self {
        Self(Animal::new(name))
    }
    fn speak(&self) -> &str {
        "Meow!"
    }
}
impl Deref for Cat {
    type Target = Animal;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

To test this implementation, we can run the following code:

Listing 10.13 Testing the polymorphism with Deref

fn main() {
    let dog = Dog::new("Rusty");
    let cat = Cat::new("Misty");
    println!("{} says: {}", dog.name(), dog.speak());
    println!("{} says: {}", cat.name(), cat.speak());
}

In conclusion, while Rust allows for polymorphism through both trait objects and the Deref trait, the idiomatic approach is to use trait objects. Emulating polymorphism with Deref is possible but not recommended due to the potential for unclear and confusing code.