我正在尝试创建一个实现共同特征的静态对象数组。所有这些结构及其大小在编译时都是已知的。但是当访问在结构上定义的字段时,编译器告诉我该字段不在类型上。
fn main() {
for &thing in ALL_THINGS {
println!("{}", thing.name)
}
}
trait Thing: Sync { }
struct SpecificThing {
name: &'static str
}
impl Thing for SpecificThing { }
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}];
error[E0609]: no field `name` on type `&dyn Thing`
--> src/main.rs:3:30
|
3 | println!("{}", thing.name)
| ^^^^
问题static array of trait objects , Create vector of objects implementing a trait in Rust , Can I have a static borrowed reference to a trait object?或 Vector of objects belonging to a trait无助于解释为什么会发生这种情况或如何解决它。
请问我这里做错了什么?有没有更好的方法来解决我还没有找到的这个任务?
最佳答案
当您定义&dyn Thing
时,您会删除有关特定数据类型的所有信息。这意味着您无法访问动态调度对象的字段。
想象一下,您在 ALL_THINGS
中有两个不同的结构:
struct SpecificThing {
name: &'static str
}
struct SpecificAnotherThing {
no_name: &'static str
}
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}, &SpecificAnotherThing { no_name: "" }];
您无法访问 name
字段,因为 trait Thing
对它实现的具体类型一无所知。因此您不能直接访问它的字段。
如果你真的需要它,你应该在 Thing
trait 中定义一个方法,它将返回你需要的值:
trait Thing: Sync {
fn name(&self) -> &str;
}
// ...
// ...
impl Thing for SpecificThing {
fn name(&self) -> &str {
self.name
}
}
或者您可以使用静态调度和代数数据类型(enum
)。
关于arrays - 如何创建实现共同特征的静态对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66947835/