Arrays 如何创建实现公共特性的静态对象数组?
我试图创建一个静态的对象数组来实现一个共同的特性。所有这些结构及其大小在编译时都是已知的。但是当访问在结构上定义的字段时,编译器告诉我该字段不在类型上Arrays 如何创建实现公共特性的静态对象数组?,arrays,rust,static,traits,Arrays,Rust,Static,Traits,我试图创建一个静态的对象数组来实现一个共同的特性。所有这些结构及其大小在编译时都是已知的。但是当访问在结构上定义的字段时,编译器告诉我该字段不在类型上 fn main() { for &thing in ALL_THINGS { println!("{}", thing.name) } } trait Thing: Sync { } struct SpecificThing { name: &'static str
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"}];
例如: 这些问题,或没有帮助解释为什么会发生这种情况或如何解决它
请问我做错了什么?有没有更好的方法来解决我还没有找到的这个任务?你不能从
&dyn Thing
中访问特定的东西.name
,因为不是所有的东西都有name
字段(忽略特征没有字段的事实)
使用dyn Thing
表明您有一组对象(结构/枚举),它们有一些共同点。所有这些共性都必须存在于Thing
中,您才能访问它们。例如,如果名称是一个常见的东西,则可以添加一个获取该名称的函数:
fn main() {
for &thing in ALL_THINGS {
println!("{}", thing.get_name())
}
}
trait Thing: Sync {
fn get_name(&self) -> &'static str;
}
struct SpecificThing {
name: &'static str
}
impl Thing for SpecificThing {
fn get_name(&self) -> &'static str {
self.name
}
}
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}];
您无法从&dyn Thing
访问specifictthing.name
,因为并非所有Things
都有name
字段(忽略特征没有字段的事实)
使用dyn Thing
表明您有一组对象(结构/枚举),它们有一些共同点。所有这些共性都必须存在于Thing
中,您才能访问它们。例如,如果名称是一个常见的东西,则可以添加一个获取该名称的函数:
fn main() {
for &thing in ALL_THINGS {
println!("{}", thing.get_name())
}
}
trait Thing: Sync {
fn get_name(&self) -> &'static str;
}
struct SpecificThing {
name: &'static str
}
impl Thing for SpecificThing {
fn get_name(&self) -> &'static str {
self.name
}
}
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}];
定义&dyn Thing
时,将删除有关特定数据类型的所有信息。这意味着您无法访问动态调度对象的字段
试想一下,在所有东西中都有两个不同的结构:
struct SpecificThing {
name: &'static str
}
struct SpecificAnotherThing {
no_name: &'static str
}
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}, &SpecificAnotherThing { no_name: "" }];
您无法访问name
字段,因为traitThing
对它实现的具体类型一无所知。因此,您不能直接访问它的字段
如果您确实需要它,您应该在Thing
trait中定义一个方法,该方法将返回您需要的值:
trait东西:同步{
fn名称(&self)->&str;
}
// ...
// ...
以牙还牙{
fn名称(&self)->&str{
姓名
}
}
或者您可以使用静态分派和代数数据类型(enum
)。当您定义&dyn Thing
时,您将删除有关特定数据类型的所有信息。这意味着您无法访问动态调度对象的字段
试想一下,在所有东西中都有两个不同的结构:
struct SpecificThing {
name: &'static str
}
struct SpecificAnotherThing {
no_name: &'static str
}
static ALL_THINGS: &'static [&dyn Thing] = &[&SpecificThing {name: "test"}, &SpecificAnotherThing { no_name: "" }];
您无法访问name
字段,因为traitThing
对它实现的具体类型一无所知。因此,您不能直接访问它的字段
如果您确实需要它,您应该在Thing
trait中定义一个方法,该方法将返回您需要的值:
trait东西:同步{
fn名称(&self)->&str;
}
// ...
// ...
以牙还牙{
fn名称(&self)->&str{
姓名
}
}
或者可以使用静态分派和代数数据类型(enum
)