- Trait Aliases (unstable feature):
- Aliasing a combination of traits for convenience.
- This feature is still unstable and not available in stable Rust.
#![feature(trait_alias)]
trait Foo = std::fmt::Debug + Send;
trait Bar = Foo + Sync;
// Use trait alias as bound on type parameter.
fn foo<T: Foo>(v: &T) {
println!("{:?}", v);
}
pub fn main() {
foo(&1);
// Use trait alias for trait objects.
let a: &Bar = &123;
println!("{:?}", a);
let b = Box::new(456) as Box<dyn Foo>;
println!("{:?}", b);
}
- Dynamic Traits and Casts:
- Casting between trait objects.
- Converting from one trait object to another.
trait Base {
fn base_method(&self);
}
trait Derived: Base {
fn derived_method(&self);
}
struct MyStruct;
impl Base for MyStruct {
fn base_method(&self) {
println!("Base method");
}
}
impl Derived for MyStruct {
fn derived_method(&self) {
println!("Derived method");
}
}
fn main() {
let obj: Box<dyn Derived> = Box::new(MyStruct);
// Cast to the base trait
let base_obj: &dyn Base = &*obj;
base_obj.base_method();
// Attempt to downcast back to the derived trait
if let Ok(derived_obj) = obj.downcast::<MyStruct>() {
derived_obj.derived_method();
}
}
- Specialization (unstable feature):
- Allowing more specific implementations of traits for specific types.
- This feature is still unstable and not available in stable Rust.