Check for trait implementation at runtime
Consider the Box<Foo>
which is Bar
, but how do we tell at runtime if the boxed traited implements other trait Foo2
.
Although Any
gives us some access to this kind of magic cast at runtime for concrete types, it explicitly does not support checking for the implementation of trait values.
The best solution we can have is to provide a mandatory fn as_foo2(&self) -> Option<&Foo2>
on the Foo trait, and explicitly define opt-in and opt-out subtraits for each binding to Bar
.
pub trait Marker { fn inst(&self) -> Option<&Action>; }
pub struct Foo; impl Marker for Foo { fn inst(&self) -> Option<&Action> { return Some(self as &Action); } }
pub struct Bar; impl Marker for Bar { fn inst(&self) -> Option<&Action> { return None; } }
pub trait Action { fn act(&self); }
impl Action for Foo {
fn act(&self) {
println!("It's a thing");
}
}
pub fn perform_action(b:&Marker) {
match b.inst() {
Some(a) => {
a.act();
},
_ => {}
}
}
pub fn main() {
let a = Box::new(Foo) as Box<Marker>;
let b = Box::new(Bar) as Box<Marker>;
perform_action(&*a);
perform_action(&*b);
}