Trait Objects - The Rust Programming Language
Let's clarify the terms and concepts related to impl Trait and dyn Trait, and delve deeper into the idea of trait objects.
impl TraitStatic Dispatch: impl Trait is used for static dispatch. This means the compiler knows the exact type at compile time, which allows for optimizations such as inlining.
Not a Trait Object: impl Trait is not a trait object. Instead, it's a way to express that a function parameter or return type implements a specific trait without naming the concrete type.
Syntax:
fn my_function(param: impl MyTrait) {
// param must implement MyTrait
}
fn returns_impl_trait() -> impl MyTrait {
MyStruct
}
dyn TraitDynamic Dispatch: dyn Trait is used for dynamic dispatch, which means the method to call is determined at runtime. This allows for polymorphism where different types can be handled through a common interface.
Trait Object: dyn Trait is a trait object. Trait objects allow for heterogeneous collections, runtime polymorphism, and more flexible APIs where the concrete type isn't known at compile time.
Syntax:
fn use_trait_object(param: &dyn MyTrait) {
// param is a trait object implementing MyTrait
}
A trait object is a way to work with types that implement a particular trait without knowing the concrete type at compile time. Trait objects are typically used with smart pointers like Box, Rc, or Arc, or with references (& or &mut).
Example:
trait MyTrait {
fn my_method(&self);
}
struct MyStruct;
impl MyTrait for MyStruct {
fn my_method(&self) {
println!("MyStruct's implementation of my_method");
}
}
fn main() {
let obj: Box<dyn MyTrait> = Box::new(MyStruct);
obj.my_method();
}
A trait object is formed when you use the dyn keyword to create a type-erased reference or smart pointer to a type that implements a trait. This type erasure allows different types to be treated uniformly based on the trait they implement.
impl Trait and dyn TraitTrait bounds are constraints that specify that a type must implement a particular trait. You can use trait bounds with both impl Trait and dyn Trait.
impl Trait with Trait Bounds