8

I have a Vec<Box<T>> where T implements Foo. Why can I not coerce it to a Vec<Box<Foo>> even though I can coerce anything of type Box<T> into a Box<Foo>? Why does the below code not compile?

use std::vec;

trait Foo {}

struct Bar {}

impl Foo for Bar {}

fn main() {
    let v = vec![Box::new(Bar {})];
    let v_1 = v as Vec<Box<Foo>>;
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Jason Teplitz
  • 654
  • 5
  • 8
  • Relevant to your interests: a [recent question on casts](http://stackoverflow.com/questions/41869048/is-there-a-trait-for-scalar-castable-types). – ljedrz Jan 27 '17 at 08:36

1 Answers1

14

Because Box<Bar> is a different size than Box<Foo>. The coercion is allowed on a single value, but here you'd have to resize the whole vector. The book goes into some detail on this in the section on Representation of Trait Objects. Short version: Box<Bar> is a pointer to a value. Box<Foo> is a pointer to a value and a pointer to a vtable.

DK.
  • 55,277
  • 5
  • 189
  • 162