Is it possible to check whether an object implements a characteristic at runtime?

trait Actor{
    fn actor(&self);
}
trait Health{
    fn health(&self);
}
struct Plant;
impl Actor for Plant{
    fn actor(&self){
        println!("Plant Actor");
    }
}
struct Monster{
    health: f32
}
impl Actor for Monster{
    fn actor(&self){
        println!("Monster Actor");
    }
}
impl Health for Monster{
    fn health(&self){
        println!("Health: {}",self.health);
    }
}
fn main() {
    let plant = Box::new(Plant);
    let monster = Box::new(Monster{health: 100f32});

    let mut actors : Vec<Box<Actor>> = Vec::new();
    actors.push(plant);
    actors.push(monster);

    for a in &actors{
        a.actor();
        /* Would this be possible?
        let health = a.get_trait_object::<Health>();
        match health{
            Some(h) => {h.health();},
            None => {println!("Has no Health trait");}
        }
        */
    }
}

I am wondering if something like this is possible?

let health = a.get_trait_object::<Health>();
match health{
    Some(h) => {h.health();},
    None => {println!("Has no Health trait");}
}
+4
source share
2 answers

Starting from 1.0, no. Rust provides no support for dynamic downgrade except Any; however, this only allows you to omit a specific concrete type, rather than arbitrary traits that a particular type implements.

I believe that you can implement such casting manually, but this will require unsafe code that will be easily mistaken; not what I want to try to summarize in the SO answer.

+5
source

This is currently not possible to do in Rust, and it will never be possible; however, you can build similar abstractions as part of your trait:

trait Actor {
    fn health(&self) -> Option<&Health>;
}

trait Health { }

impl Actor for Monster {
    fn health(&self) -> Option<&Health> { Some(self) }
}

impl Health for Monster { }

impl Actor for Plant {
    fn health(&self) -> Option<&Health> { None }
}

, - ; , - :

trait MaybeImplements<Trait: ?Sized> {
    fn as_trait_ref(&self) -> Option<&Trait>;
}

macro_rules! impl_maybe_implements {
    ($trait_:ident) => {
        impl<T: $trait_> MaybeImplements<$trait_> for T {
            fn as_trait_ref(&self) -> Option<&$trait_> {
                Some(self)
            }
        }

        impl<T: !$trait_> MaybeImplements<$trait_> for T {
            fn as_trait_ref(&self) -> Option<&$trait_> {
                None
            }
        }
    }
}

impl_maybe_implements!(Health);

trait Actor: MaybeImplements<Health> {
}

let health: Option<&Health> = actor.as_trait_ref();

, . , :

trait MaybeImplements<Trait: ?Sized> {
    fn as_trait_ref(&self) -> Option<&Trait>;
}

macro_rules! register_impl {
    ($trait_:ident for $ty:ty) => {
        impl MaybeImplements<$trait_> for $ty {
            fn as_trait_ref(&self) -> Option<$trait_> {
                Some(self)
            }
        }
    }

    (!$trait_:ident for $ty:ty) => {
        impl MaybeImplements<$trait_> for $ty {
            fn as_trait_ref(&self) -> Option<$trait_> {
                None
            }
        }
    }
}

register_impl!(Health for Monster);
register_impl!(!Health for Plant);

, , ! ! ( Rust - Turing-complete.)

+4

All Articles