检查 属性 或方法是否在运行时存在?在运行时检查 Trait 是否存在?

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

寻找正确的方法

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

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

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

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

作为最后的手段,至少如何检查特征是否已实现?

Rust 中不存在这个概念。虽然通过 Any 有一些有限的向下转换能力,这应该作为最后的手段使用。您应该做的是创建一个新特征,为您公开所有这些决定。

重用您的 my_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))
    }
}

在您的代码中,您可以调用

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