Reputation: 517
Looking for the proper way to do
if(self.MyProperty) { /* ... */ }
error: attempted access of field
MyProperty
on typeMyType
, but no field with that name was found
or
if(self.MyMethod){ /* ... */ }
error: attempted to take value of method
MyMethod
on typeMyType
As a last resort, at least how does one check if a Trait is Implemented?
Upvotes: 2
Views: 3016
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