简体   繁体   English

如何创建实现大小特征的单元结构 Vec?

[英]How to create a Vec of unit structs that implement sized trait?

I want to be able to create a Vec of unit structs that implement a sized trait (preferably without using a Box<T> ).我希望能够创建实现大小特征的单元结构 Vec(最好不使用Box<T> )。

Here is what I want to be able to do, but It fails and says that ProgrammingLanguage cannot be made into a trait object:这是我想要做的,但它失败并说ProgrammingLanguage不能成为特征 object:

struct Python;
struct Rust;

trait ProgrammingLanguage: Sized {
    fn say_hello_world() -> ();
}

impl ProgrammingLanguage for Python {...}
impl ProgrammingLanguage for Rust {...}

// Fails because ProgrammingLanguage cannot be made into a trait object
let foo = Vec::<ProgrammingLanguage>::from([Python, Rust]);

The Sized trait would not help you here. Sized特征在这里对你没有帮助。 All it can guarantee is that any particular implementation of the trait is sized, ie that you can implement it on [u8] or dyn OtherTrait ;它所能保证的是任何特定的 trait 实现都是有大小的,即你可以在[u8]dyn OtherTrait上实现它; but the dyn ProgrammingLanguage itself is always unsized, by definition.但是根据定义, dyn ProgrammingLanguage本身总是没有大小的。 The reason for this is quite simple: size of the trait object is defined as the size of an original type, and there's no way to statically guarantee that every type implementing the trait would have the same size.原因很简单:特征 object 的大小被定义为原始类型的大小,并且无法静态保证实现该特征的每个类型都具有相同的大小。

However, there's no real reason to avoid Box .但是,没有真正的理由避免Box As was mentioned in the comments, Box<UnitStruct> is essentially just a never-dereferenced dangling pointer, without any allocation at all:正如评论中提到的, Box<UnitStruct>本质上只是一个从不取消引用的悬空指针,根本没有任何分配:

struct Rust;

fn main() {
    println!("{:p}", Box::new(Rust)); // prints `0x1`
}

When you convert it to the trait object, pointer itself doesn't change - compiler just adds the vtable pointer, which is necessary for any operations with trait objects anyway.当您将其转换为特征 object 时,指针本身不会改变 - 编译器只会添加 vtable 指针,这对于任何使用特征对象的操作都是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM