简体   繁体   中英

Check if property or method exists at runtime? Check if Trait exists at runtime?

Looking for the proper way to do

if(self.MyProperty) { /* ... */ }

error: attempted access of field MyProperty on type MyType , but no field with that name was found

or

if(self.MyMethod){ /* ... */ }

error: attempted to take value of method MyMethod on type MyType

As a last resort, at least how does one check if a Trait is Implemented?

This concept doesn't exist in Rust. While there is some limited downcast capability through Any , this should be used as a last resort. What you should do is create a new trait that exposes all of these decisions for you.

Reusing your example of a my_method method:

trait YourTrait {
    fn try_my_method(&self, arg: SomeArg) -> Option<MyMethodResult> {
        None
    }
}

impl YourTrait for SomeType {
    fn try_my_method(&self, arg: SomeArg) -> Option<MyMethodResult> {
        Some(self.my_method(arg))
    }
}

In your code you can then call

if let Some(result) = self.try_my_method() {
    /* ... */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM