Is polymorphism with sized traits possible in rust

Viewed 170

I am using a library that exposes a trait which requires it to be Sized.

I am using an object that implements this trait, and am trying to create an array that include all those instances. 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.

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); 
}
1 Answers

dyn Trait is always unsized by definition, because it allows the object behind it to have any size from 0 to isize::MAX.

To have a fixed-size object and polymorphism, use an enum. You can then add impl on the enum itself that dispatches calls to the variants. There are some hacky crates that automate that.

Related