1

I have the following struct defined in my project:

pub struct HitableList <'a> {
    pub list : Vec<Box<dyn Hitable + 'a>>
}

impl <'a> HitableList <'a> {
    pub fn new (l : &Vec<Box<dyn Hitable + 'a>>) -> HitableList<'a> {
        HitableList {list : *l}
    }                                                                                         
}

where Hitable is a trait that is implemented by HitableList

Then later on I want to create a HitableList like so

let list = vec![Box::new(Sphere::new(Vec3::new(0f32, 0f32, -1f32), 0.5f32)), Box::new(Sphere::new(Vec3::new(0f32, -100.5f32, -1f32), 100f32))];
let world = &HitableList::new(&list);

Spheres in my code also implement the Hitable trait

When I run that last code however I get the following compilation error:

error[E0308]: mismatched types
--> src/image_gen/many_spheres.rs:39:35
   |     let world = &HitableList::new(&list);
   |                  ---------------- ^^^^^ expected trait object `dyn Hitable`, found struct `Sphere`
   |                  |
   |                  arguments to this function are incorrect
   |
   = note: expected reference `&Vec<Box<dyn Hitable>>`
              found reference `&Vec<Box<Sphere>>`

I'm using boxes to contemplate the Vector having different objects that implement the Hitable trait. However, I have no clue why a Box is not a Box

What am I doing wrong and how do I fix this? Thanks in advance

  • I'm not sure, but I suspect `Box` and `Box` are two different types and you have to create a new vector with the proper type, there is no way to directly cast one vector to another (just like with `Vec` and `Vec`). I'd try something like `let world = list.into_iter().map(|x| x as Box).collect::>()` – yeputons Jan 04 '23 at 23:30
  • 1
    For Box in particular, this automatic conversion works. But for noting else, really. See here: https://stackoverflow.com/questions/58683548/how-to-coerce-a-vec-of-structs-to-a-vec-of-trait-objects – cadolphs Jan 04 '23 at 23:32
  • is there another way of going about this? – Francisco José Letterio Jan 04 '23 at 23:35
  • 1
    Yes. As pointed out in the post I linked, you'll need to coerce each item of the vector individually. – cadolphs Jan 05 '23 at 03:50

0 Answers0