【发布时间】:2021-04-05 03:14:25
【问题描述】:
我正在尝试创建一个实现共同特征的静态对象数组。所有这些结构及其大小在编译时都是已知的。但是当访问结构上定义的字段时,编译器会告诉我该字段不在类型上。
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 无助于解释为什么会发生这种情况或如何解决它。
请问我在这里做错了什么?有没有更好的方法来解决这个我还没有找到的任务?
【问题讨论】: