0

Playground

MyCode uses another library 'Their...' - especially needed is 'TheirShadow'.

I'm trying to execute a function 'draw' from MyDrawing-Trait, which I implement for MyGraph-Struct where
T: TheirShadow<Output = TheirOutput>

The problem:
even though, that the where-clause requires TheirShadow Output=TheirOutput, the compiler claims that it doesnt.

the method `draw` exists but the following trait bounds were not satisfied:
            `<Box<dyn TheirShadow<Output = TheirOutput>> as TheirShadow>::Output = TheirOutput`
            which is required by `MyGraph<Box<dyn TheirShadow<Output = TheirOutput>>>: MyDrawing`
            `Box<dyn TheirShadow<Output = TheirOutput>>: TheirShadow`
            which is required by `MyGraph<Box<dyn TheirShadow<Output = TheirOutput>>>: MyDrawing`

I'm struggling figuring out, how to write the where clause, so that the needed traits are included - do you have insights on that?

Thanks!

pub struct MyGraph<T> {
    id: i32,
    shape: T
}
pub trait MyDrawing {
    fn draw(self, distance: i32);
}

impl<T> MyDrawing for MyGraph<T> 
where
T: TheirShadow<Output = TheirOutput>
{
    fn draw(self, distance: i32){
        self.shape.cast_shadow(&distance);
        println!("Graph has a Shape with Shadow");
    }
}

fn main()
{
    let p = TheirPoint {
        x: 3,
        y: 3
    };
    
    let l = TheirLine {
        start: p,
        end: p
    };
    
    let mut vec_shapes: Vec<Box<dyn TheirShadow<Output=TheirOutput>>> = vec![Box::new(p), Box::new(l)];
    let vec_graphs: Vec<MyGraph<Box<dyn TheirShadow<Output=TheirOutput>>>> = createGraph(vec_shapes);
    for graph in vec_graphs {
        graph.draw(&3);
    }
}


fn createGraph<T>(shapes: Vec<T>) -> Vec<MyGraph<T>>
 {
    let mut graphs = vec![];
    let mut i = 0;
    for shape in shapes{

        let graph = MyGraph {
             id: i,
             shape: shape
        };
    
        graphs.push(graph);
        let mut i = i+1;
    }
    graphs
}


til
  • 832
  • 11
  • 27
  • 2
    `MyGraph` only implements `draw` if `T: MyShadow`, but a trait object doesn't implement the trait OOTB, so `Box>` may not implement `TheirShadow`. See [this previous question](https://stackoverflow.com/questions/33041736/trait-implementation-for-both-a-trait-object-and-for-direct-implementors-of-the). – Masklinn Dec 01 '20 at 11:18

1 Answers1

1

Based on the answer, Masklinn recommended, the following worked playground

impl<T> MyDrawing for MyGraph<Box<T>> 
where
T: TheirShadow<Output = TheirOutput> + ?Sized
{
    fn draw(self, distance: i32){
        self.shape.cast_shadow(&distance);
        println!("Graph has a Shape with Shadow");
    }
}

til
  • 832
  • 11
  • 27