gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:27:16 26 4
gpt4 key购买 nike

寻找正确的方法

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

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

最佳答案

这个概念在 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() {
/* ... */
}

关于methods - 检查运行时属性或方法是否存在?在运行时检查 Trait 是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45049287/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com