Sub topic 3
Which Traits Can Be Trait Objects
This chapter assumes basic Rust ownership, borrowing, structs, traits, generics, and Box.
Dyn compatibility
A trait is dyn compatible when Rust can create a dyn Trait value from it. Older Rust documentation called this “object safe.”
A dyn-compatible trait must avoid features that require knowing the concrete type at compile time:
- No generic methods.
- No associated constants.
- Methods must use a dispatchable receiver such as
&self,&mut self, orBox<Self>. - Methods must not return
Selfor useSelfin other arguments. - Methods using
impl Traitorasync fnare not directly dyn compatible.
Associated types are allowed. A method can also be excluded from the trait object with where Self: Sized.
use std::any::Any;
use std::str::FromStr;
trait Store {
fn get(&self, key: &str) -> Option<String>;
fn parse<T: FromStr>(&self, key: &str) -> Option<T>
where
Self: Sized,
{
self.get(key)?.parse().ok()
}
}
struct Mem;
impl Store for Mem {
fn get(&self, key: &str) -> Option<String> {
Some(key.len().to_string())
}
}
trait Readable {
fn read(&self) -> String;
}
trait Writable: Readable {
fn write(&self);
}
struct Document;
impl Readable for Document {
fn read(&self) -> String {
String::from("data")
}
}
impl Writable for Document {
fn write(&self) {}
}
trait Component: Any {
fn as_any(&self) -> &dyn Any;
}
struct Health(u32);
impl Component for Health {
fn as_any(&self) -> &dyn Any {
self
}
}
fn main() {
let concrete = Mem;
let length: Option<u32> = concrete.parse("abc");
println!("{length:?}");
let store: Box<dyn Store> = Box::new(Mem);
println!("{:?}", store.get("abcd"));
let document = Document;
let readable: &dyn Readable = &document; // supertrait upcasting
let component: Box<dyn Component> = Box::new(Health(10));
if let Some(health) = component.as_any().downcast_ref::<Health>() {
println!("{} {}", readable.read(), health.0);
}
}Lifetimes, `Send`, and `Sync`
A trait object can carry an explicit lifetime:
&'a dyn Storecannot outlive the borrowed implementation.Box<dyn Store + 'a>may contain a value valid for'a.Box<dyn Store>commonly meansBox<dyn Store + 'static>because the box owns its value.
Send allows a value to move between threads. Sync allows shared references to be used between threads. Add these bounds when required:
Box<dyn Store + Send>
Arc<dyn Store + Send + Sync>Supertraits and upcasting
If Writable: Readable, every writable value is readable. Rust can coerce &dyn Writable to &dyn Readable. This is called trait upcasting. It exposes the smaller interface without recovering the concrete type.
Recovering concrete types
dyn Any supports checked downcasting. A trait can expose as_any, then callers can request a specific type. downcast_ref returns None when the type does not match. Prefer trait methods when possible; downcasting couples code to concrete types.
Exercise
Why can Store be used as dyn Store even though it has a generic method?
Show answer
The generic method has where Self: Sized, so it is unavailable through the trait object and is omitted from its vtable.