HTDE
HTDE

Reputation: 517

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?

Upvotes: 2

Views: 3016

Answers (1)

oli_obk
oli_obk

Reputation: 31163

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() {
    /* ... */
}

Upvotes: 3

Related Questions