sadtroll
sadtroll

Reputation: 191

Is it possible to have a vector of traits bounded by Sized?

I am trying to see if there is any way to implement a vector of sized traits. I know about trait objects, and using Vec<Box<dyn traitName>> if traitName is ?Sized. But what if I have (playground):

trait A: Sized {}

struct B {
    c: u64,
}

impl A for B {}

fn lol() -> Vec<A> {
    let mut a: Vec<A> = Vec::new();
    
    let b = B { c: 2} ;
    
    a.push(b);
    
    a
}

The error I get is:

error[E0782]: trait objects must include the `dyn` keyword
 --> src/main.rs:8:17
  |
8 | fn lol() -> Vec<A> {
  |                 ^
  |
help: add `dyn` keyword before this trait
  |
8 - fn lol() -> Vec<A> {
8 + fn lol() -> Vec<dyn A> {

but to fix that I have to use trait objects, which is not possible since A: Sized. Any way to fix this or is it impossible?

Upvotes: 1

Views: 355

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71310

A where A is a trait is just an old syntax (forbidden in the 2021 edition) to dyn A. You can't create A or dyn A if A: Sized, ever.

if you'll run this with the 2018 edition, you'll get errors "the size for values of type (dyn A + 'static) cannot be known at compilation time".

Upvotes: 1

Related Questions