我试图创建一个实现共同特征的对象静态数组。所有这些结构体和它们的大小在编译时已知。但是当访问在结构体上定义的字段时,编译器告诉我该字段不属于该类型。
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、在Rust中创建实现特质的对象向量的问题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不能解释为什么会发生这种情况,也无法说明如何解决它。
请问我做错了什么?是否有更好的方法来解决我还没有找到的任务?