简体   繁体   English

rust 中是否可能存在具有大小特征的多态性

[英]Is polymorphism with sized traits possible in rust

I am using a library that exposes a trait which requires it to be Sized .我正在使用一个库,该库公开了一个要求它为Sized的特征。

I am using an object that implements this trait, and am trying to create an array that include all those instances.我正在使用实现此特征的 object,并尝试创建一个包含所有这些实例的数组。 With a non-sized trait I would use something like Vec<Box<dyn MyNonSizedTrait>> , but with the Sized trait it's impossible, the compiler complains with the trait MySizedTrait cannot be made into an object .对于非大小特征,我会使用Vec<Box<dyn MyNonSizedTrait>>之类的东西,但是对于Sized特征,这是不可能的,编译器会抱怨the trait MySizedTrait cannot be made into an object

Is there any way to work around that?有没有办法解决这个问题?

Here is an example of what I'm trying to do:这是我正在尝试做的一个例子:

trait A: Sized {
    fn do_something(&self);  
}
    
struct B;

impl A for B {
    fn do_something(&self){
        println!("This is B")
    }
}
    
struct C;
    
impl A for C {
    fn do_something(&self) {
        println!("This is C")
    }
}
    
    
fn my_do_something(d: &[Box<dyn A>]) {
    for i in d {
        i.do_something(); 
    }
}
    
fn main() {
    let mut d: Vec<Box<dyn A>> = Vec::new();
    d.push(Box::new(B));  
    d.push(Box::new(C)); 
    my_do_something(&d); 
}

dyn Trait is always unsized by definition, because it allows the object behind it to have any size from 0 to isize::MAX . dyn Trait根据定义始终是未调整大小的,因为它允许其后面的 object 具有从0isize::MAX的任何大小。

To have a fixed-size object and polymorphism, use an enum .要拥有固定大小的 object 和多态性,请使用enum You can then add impl on the enum itself that dispatches calls to the variants.然后,您可以在分配对变体的调用的enum本身上添加impl There are some hacky crates that automate that.有一些hacky crates可以自动执行此操作。

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

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