0

TL;DR;

struc: TheirPoint, TheirLine
trait: TheirShadow, MySpecialShadow

TheirShadow for TheirPoint
TheirShadow for TheirLine

MySpecialShadow for TheirPoint
MySpecialShadow for TheirLine

let vec_shapes: Vec<Box<dyn TheirShadow>> = vec![Box::new(point), Box::new(line)];

Problem:

for shape in vec_shapes {
  shape.myspecialshadow_function()
//doesnt work - what can be done? Downcast? - but how to handle different types? 
}

Long version: Playground

I'm working with a lib <TheirThings> and use that in <MyCode>.
Specifically, I use different of their Shapes (TheirPoint, TheirLine) which have all a common

  • output: TheirOutput which is an enum
  • function: cast_shadow provided by Trait TheirShadow, which returns TheirOutput

I have a Vec<Box<dyn TheirShadow>>

let vec_shapes: Vec<Box<dyn TheirShadow<Output=TheirOutput>>> = vec![Box::new(p), Box::new(l)];

I've created a Trait MySpecialShadow, having a function special_shadow which I implement individually for TheirPoint, TheirLine, and I struggle being able to call it during a loop over vec_shapes.

I tried the following without success

let vec_shapes: Vec<Box<dyn TheirShadow<Output=TheirOutput, MySpecialShadow>>> = vec![Box::new(p), Box::new(l)];

Do you have a recommendation how to structure the code so that a mixed vec based on dyn Trait enables call ability to other traits? Downcasting? How would that look like for a mixed vec?

Thanks for ideas!

til
  • 832
  • 11
  • 27

1 Answers1

0

Based on the hint @pretzelhammer commented, I've been able to end up with this playground, which works even if not the same struct gets implemented for the different traits, but the struct with trait 1 wrapped in struct with trait 2.

I'm still not sure, if thats the smartest way to go forward, so if there are concepts out there to better achieve such a solution, please share!

til
  • 832
  • 11
  • 27