Is it possible to check if an object implements a trait at runtime?

后端 未结 2 1134
一个人的身影
一个人的身影 2020-12-10 12:45
trait Actor{
    fn actor(&self);
}
trait Health{
    fn health(&self);
}
struct Plant;
impl Actor for Plant{
    fn actor(&self){
        println!(\"Pla         


        
2条回答
  •  失恋的感觉
    2020-12-10 13:05

    As of 1.0, no. Rust doesn't provide any dynamic downcasting support, with the exception of Any; however, that only allows you to downcast to a value's specific concrete type, not to arbitrary traits that said concrete type implements.

    I believe you could implement such casting manually, but that would require unsafe code that would be easy to get wrong; not the sort of thing I want to try and summarise in an SO answer.

提交回复
热议问题