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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值