rust - 方法 `draw`存在,但在Vec <Box <dyn Trait >>中不满足以下特征范围,Compilernote应该满足吗?

Posted 跨链技术践行者

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了rust - 方法 `draw`存在,但在Vec <Box <dyn Trait >>中不满足以下特征范围,Compilernote应该满足吗?相关的知识,希望对你有一定的参考价值。

This question already has an answer here:
Trait implementation for both a trait object and for direct implementors of the trait

(1个答案)


3个月前关闭。




Playground
MyCode使用另一个库'Their ...'-特别需要的是'TheirShadow'。
我正在尝试从MyDrawing-Trait中执行功能“draw”,该功能已实现
对于MyGraph-Struct,其中
T:他们的影子<输出=他们的输出>
问题:
即使where子句要求使用他们的ShadowOutput = TheirOutput,编译器也声称不需要。
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`
我正在努力弄清楚如何编写where子句,以便包括所需的特征-您对此有见解吗?
谢谢!
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
}


最佳答案

根据答案,Masklinn建议使用以下方法
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");
    }
}

关于rust - 方法 `draw`存在,但在Vec <Box <dyn Trait >>中不满足以下特征范围,Compilernote应该满足吗? [复制],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65089208/

以上是关于rust - 方法 `draw`存在,但在Vec <Box <dyn Trait >>中不满足以下特征范围,Compilernote应该满足吗?的主要内容,如果未能解决你的问题,请参考以下文章

Rust 存在重复元素 两种解法

Rust语言圣经32 - 动态数组Vec

如何在 rust 中迭代 vec 或 slice 的前缀或后缀?

rust - 如何在Vec上更新或插入?

Rust学习教程32 - 动态数组Vec

Rust学习教程32 - 动态数组Vec