Rust trait object
Created By: chatGPT
Rust allows the creation of trait objects to enable dynamic dispatch. A trait object is a way to use traits for types that are known only at runtime. This allows for more flexible and extensible code. Trait objects are created by using a reference to a trait (
&dyn TraitType
or Box<dyn TraitType>
).// Define a trait
trait Shape {
fn area(&self) -> f64;
}
// Implement the trait for different types
struct Circle {
radius: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.radius * self.radius
}
}
struct Rectangle {
width: f64,
height: f64,
}
impl Shape for Rectangle {
fn area(&self) -> f64 {
self.width * self.height
}
}
// Using trait objects
fn print_area(shape: &dyn Shape) {
println!("Area: {}", shape.area());
}
To use trait objects, you can create instances of your structs and pass them to functions that expect a trait object. Here’s how you can create instances and call a function using trait objects.
// Create instances of Circle and Rectangle
fn main() {
let circle = Circle { radius: 2.0 };
let rectangle = Rectangle { width: 3.0, height: 4.0 };
// Pass references as trait objects
print_area(&circle);
print_area(&rectangle);
}